How to parse Google weather API using NSXML? - iphone

i want to parse google weather API using NSXML so please give me some Guidance for this.
This is My url
and i have taken such kind of steps:
NSURL *url = [NSURL URLWithString:#"http://www.google.com/ig/api?weather=Ahemdabad"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection){
webData = [[NSMutableData data] retain];
NSLog( #"connection established");
}
else {
NSLog(#"theConnection is NULL");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connectio
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"thexml=============>%#", theXML);
[theXML release];
if(parser)
{
[parser release];
}
parser = [[NSXMLParser alloc]initWithData:webData];
[parser setDelegate: self];
[parser setShouldResolveExternalEntities: YES];
[parser parse];
[connection release];
[webData release];
}

hey ankit you can get this code if at all its helpful to you no need to establish connection
just use this method
-(id)initWithURL:(NSURL*)url arrayRootObjectTags:(NSArray*)arrTags sel:(SEL)seletor andHandler:(NSObject*)handler{
if(self = [super init] ){
self.mainArray=arrTags;
self.MainHandler=handler;
self.targetSelector=seletor;
NSLog(#"%#",[url description]);
NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:30];
con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
if(con){
myWebData=[[NSMutableData data] retain];
} else {
[MainHandler performSelector:#selector(targetSelector:) withObject:nil];
}
}
return self;
}
also the other supporting method
-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict {
if([elementName isEqualToString:#"html"] || [elementName isEqualToString:#"HTML"]){
didGetHTML=YES; [self parserDidEndDocument:parser];
} else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML) {
objectsArray=[[NSMutableArray alloc] init];
tmpD=[[NSMutableDictionary alloc] init];
if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];
} else if([[mainArray objectAtIndex:0] isEqualToString:elementName] && !didGetHTML ) {
objectsArray=[[NSMutableArray alloc] init];
if(tmpOther==nil) tmpOther=[[NSMutableDictionary alloc] init];
} else if([[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML ) {
tmpD=[[NSMutableDictionary alloc] init];
} else if([mainArray containsObject:elementName] && !didGetHTML){
[tmpD setValue:[attributeDict valueForKey:#"data"] forKey:elementName];
}
}
-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string {
if(tmpString==nil && !didGetHTML){
tmpString=[[NSString alloc] initWithString:string];
} else if(!didGetHTML){
NSString *t=[NSString stringWithString:tmpString];
if([tmpString retainCount]>0) { [tmpString release]; tmpString=nil; }
tmpString=[[NSString alloc] initWithFormat:#"%#%#",t,string];
}
}
-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
if([[mainArray objectAtIndex:0] isEqualToString:elementName] && [[mainArray objectAtIndex:1] isEqualToString:elementName] && !didGetHTML){
[objectsArray addObject:tmpD];
} else if([elementName isEqualToString:[mainArray objectAtIndex:1]] && !didGetHTML){
[objectsArray addObject:tmpD];
[tmpD release]; tmpD=nil;
} else if([mainArray containsObject:elementName] && !didGetHTML) {
if(![tmpD valueForKey:elementName]){
[tmpD setValue:tmpString forKey:elementName];
}
[tmpString release]; tmpString=nil;
} else {
[tmpOther setValue:tmpString forKey:elementName];
[tmpString release]; tmpString=nil;
}
}
and simply call the initwith url method from which ever class you have written this method
just you have to give root tag object tag and element tag of a particular object tag and also give selector after that take the response in dictionary and they take it in array and display the result according to your value for key

Related

how to go to another ViewController after successful login

I am newbie for iPhone application. I have followed this tutorial for login from iPhone.
I have php file as below.
index.php
<?php
$user = $_POST['uname'];
if ($user == 'user') {
echo "Welcome to my site...";
} else {
echo "Invalid User";
}
?>
When I run application and enter username as user and password as some text, I get output as Welcome to my site....
Now instead of welcome message, I wanna go to my welcome screen i.e. View Controller that I have on story board. Any idea how to get this done?
Full code is as below.
-(IBAction)buttonClick:(id)sender
{
greeting.text= #"";
NSString* username = nameInput.text;
NSString* pass = passInput.text;
greeting.hidden = NO;
if([nameInput.text isEqualToString:#"" ] && [passInput.text isEqualToString:#""])
{
greeting.text = #"Please enter username and password.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
if([nameInput.text isEqualToString:#"" ])
{
greeting.text = #"Please enter username.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
if([passInput.text isEqualToString:#""])
{
greeting.text = #"Please enter password.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
NSString *post = [[NSString alloc] initWithFormat:#"uname=%#&pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://localhost:8888/PhPTesting/index.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
indicator.hidden = NO;
webData = [[NSMutableData data] retain];
}
else
{
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
indicator.hidden = YES;
}
You can do this :
if ([loginStatus isEqualToString:#"Welcome to my site..."]) {
// Show welcome view controller
NextViewController *nextViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"myNextView"];
[self.navigationController pushViewController:nextViewController animated:YES];
} else {
greeting.text = #"Login was not correct";
}
Here , #"myNextView" is a NextView Identifier.
You can check the result
if ([loginStatus isEqualToString:#"Welcome to my site..."]) {
// Show welcome view controller
} else {
greeting.text = #"Login was not correct";
}
I also suggest returning a more helpful string via PHP
UPDATE
There are tons of tutorials for presenting a new view.
Check out this here: Programatically Switching Views in Cocoa Touch

cfstring length message sent to deallocated instance?

I m doing the concept of autocomplete feature for a textField and in doing so I m getting the following error:
"cfstring length message sent to deallocated instance"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if( textField == txtcity)
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
subString2=[NSString stringWithFormat:#"%#",substring];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData = data;
[data release];
NSURL *jsonUrl =[NSURL URLWithString:[NSString stringWithFormat:#"http://210.90.32.122/services/AutoService.svc/GetCities/?p=%#&k=%#",substring,txtId.text]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonUrl];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
self.connection = connection;
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
parser = [[NSXMLParser alloc] initWithData:receivedData];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
NSLog(#"%#",arr2);
if([arr2 count]!=0)
{
self.autocompleteUrls = [[NSMutableArray alloc] init];
if(autocompleteTableView)
[autocompleteTableView removeFromSuperview];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(88, 428, 200,[arr2 count]*20) style:UITableViewStyleGrouped];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.rowHeight=20;
[self.view addSubview:autocompleteTableView];
for(int i=0;i<[arr2 count];i++)
{
NSString *curString = [[arr2 objectAtIndex:i] valueForKey:#"Name"];
NSRange substringRange = [curString rangeOfString:subString2]; //error at this line
if (substringRange.location == 0)
[autocompleteUrls addObject:curString];
}
}
[autocompleteTableView reloadData];
txtcity.text=subString2;
[txtcity resignFirstResponder];
}
my subString2 is becoming null.But I have retained it while decalring
#property(nonatomic,retain)NSString *subString2;
Where Im going wrong.Couldn't understand where it is being deallocated..
You're not actually retain it. You're setting the object variable subString2 not though the property, that is the reason. Try this:
self.subString2 = [NSString stringWithFormat:#"%#",substring];
But it is not very good practise to get to the object variables from the object through the properties. There is two options:
[subString2 release];
subString2 = [[NSString stringWithFormat:#"%#",substring] copy];
OR
[subString2 release];
subString2 = [[NSString stringWithFormat:#"%#",substring] retain];

About how to use NSThread

I'm an iPhone developer.
I studied about how to use NSThread. So I created source code.
But, I'm not sure about my source code whether good or bad.
-(void)check_threadEnd
{
if ([_thread isFinished]) {
threadCount++;
if (threadCount == 4) {
[self performSelector:#selector(removeActivityView) withObject:nil afterDelay:0.0];
[self.tableView reloadData];
}
}
}
Sometimes, threadCount doesn't become 4.
So, ActiveView is worked continual without stopping.
Turn the timer after a period of time, remove ActiveView?
I'll give you some advice please.
-(IBAction)click_ServerSync:(id)sender
{
if ([util checkNetwork]) {
threadCount = 0 ;
[self displayActivityView];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue setMaxConcurrentOperationCount:4];
_thread = [[NSThread alloc] initWithTarget:self selector:#selector(_th) object:nil];
[_thread start];
}
}
-(void)_th
{
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML1" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML2" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML3" waitUntilDone:NO];
[self performSelectorOnMainThread:#selector(LoadXml:) withObject:#"XML4" waitUntilDone:NO];
}
-(void)LoadXml:(NSString*)P_VAL
{
NSString *smsURL = [NSString stringWithFormat:#"%#%#.asp", XML_URL, P_VAL];
NSString *sendAuthInfo = [NSString stringWithFormat:#"A=%#&B=%d&C=%#&D=%#" , A, B, C, D ];
NSString *val = [sendAuthInfo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:smsURL]]autorelease];
[request setURL:[NSURL URLWithString:smsURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [val dataUsingEncoding: NSUTF8StringEncoding]];
[self startAsyncLoad:request tag:P_VAL];
}
- (void)startAsyncLoad:(NSMutableURLRequest*)request tag:(NSString*)tag {
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
if (connection) {
[receivedData setObject:[[NSMutableData data] retain] forKey:connection.tag];
}
}
- (NSMutableData*)dataForConnection:(CustomURLConnection*)connection {
NSMutableData *data = [receivedData objectForKey:connection.tag];
return data;
}
-(void)check_threadEnd
{
if ([_thread isFinished]) {
threadCount++;
if (threadCount == 4) {
[self performSelector:#selector(removeActivityView) withObject:nil afterDelay:0.0];
[self.tableView reloadData];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[dataForConnection appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(#" connection connectionDidFinishLoading : %d", [connection retainCount]);
NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithData:dataForConnection] autorelease];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:(id)parser];
parser.viewDelegate = (id)self;
[xmlParser parse]; // xml parser
}
Do you have a reason as to why you are opting for NSThread over NSOperation? NSOperation abstracts away a lot of the lower-level thing you would have to worry about with NSThread. I would strongly recommend you read up on this concurrency programming guide from Apple.
Pay attention to the last section, Migrating Away From Threads, as it talks about additional alternatives that can help you write robust, clean code.

Asynchronous connection not getting called

I want to create two connections in a single view controller class. I am using NSOperationQueue for this purpose. The two connections are created in two functions and push inside the queue .The problem is delegates are not called. Please help me out. Thanks you in advance
- (void)viewDidLoad {
[super viewDidLoad];
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
NSInvocationOperation *invOperation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(createConnection1) object:nil];
NSInvocationOperation *invOperation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(createConnection2) object:nil];
NSArray *ops=[[NSArray alloc] initWithObjects:invOperation1,invOperation2,nil];
[queue addOperations:ops waitUntilFinished:YES];
}
-(void) createConnection1{
//create connection
NSLog(#"Create Connection 1");
url1 =[[NSMutableString alloc] initWithFormat:#"http://www.google.com/ig/api?weather=New Delhi"];
NSURLRequest *theRequest1=[NSURLRequest requestWithURL:[NSURL URLWithString:url1]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
theConnection1=[[NSURLConnection alloc] initWithRequest:theRequest1 delegate:self];
if (theConnection1) {
connectionCreated1=YES;
receivedData1 = [[NSMutableData data] retain];
NSLog(#"received data 1 %#",receivedData1);
//[theConnection1 setDelegate:self];
}
}
-(void) createConnection2{
//create connection
NSLog(#"Create Connection 2");
url2 =[[NSMutableString alloc] initWithFormat:#"http://www.google.com/ig/api?weather=Chennai"];
NSURLRequest *theRequest2=[NSURLRequest requestWithURL:[NSURL URLWithString:url2]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
theConnection2=[[NSURLConnection alloc] initWithRequest:theRequest2 delegate:self];
if (theConnection2) {
connectionCreated2=YES;
receivedData2 = [[NSMutableData data] retain];
//[theConnection2 setDelegate:self];
NSLog(#"received data 2 %#",receivedData2);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if (connectionCreated1==YES) {
[receivedData1 setLength:0];
}
else if (connectionCreated2==YES) {
[receivedData2 setLength:0];
}
else {
NSLog(#"did not receive response");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connectionCreated1==YES) {
[theConnection1 release];
xmlParser1 = [[NSXMLParser alloc] initWithData:receivedData1];
[xmlParser1 setDelegate:self];
[xmlParser1 parse];
}
else if(connectionCreated2==YES){
[theConnection2 release];
xmlParser2 = [[NSXMLParser alloc] initWithData:receivedData2];
[xmlParser2 setDelegate:self];
[xmlParser2 parse];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"connection failed" message:#"" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connectionCreated1==YES) {
[receivedData1 appendData:data];
}
else if(connectionCreated2==YES) {
[receivedData2 appendData:data];
}
else {
NSLog(#"data not received");
}
}
The URL you have given in the first link seems to be borken ... look at this "http://www.google.com/ig/api?weather=New Delhi".. there is space between new delhi. try this instead http://www.google.com/ig/api?weather=New+Delhi

How to use the JSON Parsing?

I am a fresher. I don't know how to use JSON for Parsing .I am really very confuse because the tutorial i have read are out dated because apple has deprecated all the API's and documents .Thats what i found .So anyone can give me the start to play with JSON?
You can use SBJSON
You can find code at GITHUB
Here's some links on "Picking the best JSON library":
Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
Best JSON library to use when developing an iPhone application?
And now for the shameless plug for my own JSON parsing solution, JSONKit:
What's the most efficient way of converting a 10 MB JSON response into an NSDictionary?
Cocoa JSON parsing libraries, part 2
You need to use third-party code to parse JSON. Three popular libraries/frameworks are:
SBJSON, aka json-framework
TouchJSON
yajl-objc
Choose one of them, download its source code and add it do your project.
You can use your custom framwork for it just as below
#import <Foundation/Foundation.h>
#import "SVProgressHUD.h"
#protocol JsonDataDelegate <NSObject>
#required
- (void) JsonprocessSuccessful: (NSString *)receivedData;
-(void) JsonprocessFail;
#end
#interface JsonRest : NSObject
{
id <JsonDataDelegate> delegate;
NSURLConnection *theConnection;
NSMutableData *webData;
BOOL HadGotResponse;
BOOL HasFailedConnection;
UIAlertView *alert;
}
#property (retain) id delegate;
#property(nonatomic,retain) NSURLConnection *theConnection;
#property (nonatomic)BOOL HadGotResponse;
#property (nonatomic)BOOL HasFailedConnection;
-(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter;
-(void)Set2Defaults;
#end
#import "JsonRest.h"
#define BASE_URL #"http://www.abc.com"
#define DOMAIN #"GETLIST"
#implementation JsonRest
#synthesize delegate,HadGotResponse,HasFailedConnection,theConnection;
- (id)init
{
if (self)
{
// Initialization code.
//appdel = (ReachCastAppDelegate*)[[UIApplication sharedApplication]delegate];
}
return self;
}
-(void)GetServiceCall:(NSString *)url Paraqmeter:(NSString*)parameter
{
[SVProgressHUD startActivity : #"Loading..."];
NSString *strUrl=[NSString stringWithFormat:#"%#%#?%#",BASE_URL,url,parameter];
NSURL *url1=[NSURL URLWithString:strUrl];
NSLog(#"domainURL :: %#",strUrl);
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
[req setTimeoutInterval:60.0];
[req setHTTPMethod:#"GET"];
// if([HttpMethod isEqualToString:#"GET"])
// {
// [req setHTTPMethod:HttpMethod];
//
// }
// else if([HttpMethod isEqualToString:#"PUT"])
// {
// NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
//
// [req setValue:valueforput forHTTPHeaderField:#"Content-type"];
// [req setHTTPMethod:HttpMethod];
// [req setHTTPBody: requestData];
//
// }
// else if ([HttpMethod isEqualToString:#"POST"]){
//
// NSData *requestData = [NSData dataWithBytes: [BodyString UTF8String] length: [BodyString length]];
//
// [req setValue:valueforput forHTTPHeaderField:#"Content-type"];
// [req setHTTPMethod:HttpMethod];
// [req setHTTPBody: requestData];
//
// }
if(theConnection)
[self Set2Defaults];
theConnection=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(theConnection)
webData=[[NSMutableData data]retain];
else
NSLog(#"Connection Failed !!!");
NSLog(#"Has got response");
}
-(void)Set2Defaults {
if (webData != nil){
[webData release];
webData = nil;
}
if (theConnection != nil) {
[theConnection release];
if (theConnection != nil)
theConnection = nil;
}
}
#pragma mark -
#pragma mark NSURL Connection Delegate methods
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) respons{
[webData setLength: 0];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)respons;
int statusCode = [httpResponse statusCode];
NSLog(#"statusCode ---- >> %d",statusCode);
if (200 != statusCode) {
// if (401 == statusCode) {
}
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
[SVProgressHUD stopActivity];
[self Set2Defaults];
self.HadGotResponse=NO;
self.HasFailedConnection=YES;
// txtWindSpeed.text = #"";
[[self delegate] JsonprocessFail];
NSLog(#"Connection Failed!!!");
//[self HideLoadingDialogue];
alert = [[[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Internet Connection Failed.Please try again." delegate:self cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
//alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y, alert.frame.size.width, 130);
NSLog(#"%F",alert.frame.origin.y);
[alert show];
alert.frame=CGRectMake(alert.frame.origin.x, alert.frame.origin.y+25, alert.frame.size.width, 130);
//[noConnect release];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(timerCall) userInfo:nil repeats:NO];
}
-(void)timerCall
{
[alert dismissWithClickedButtonIndex:0 animated:TRUE];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[SVProgressHUD stopActivity];
self.HasFailedConnection=NO;
NSString *theXML;
theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSASCIIStringEncoding];
//NSLog(#"theXML Values : %#", theXML);
//self.ResponseDict = [theXML JSONValue];
[[self delegate] JsonprocessSuccessful:theXML];
[theXML release];
}
-(void)dealloc
{
if (webData != nil){
[webData release];
webData = nil;
}
if (theConnection != nil) {
[theConnection release];
if (theConnection != nil)
theConnection = nil;
}
[super dealloc];
// [ResponseDict release];
}
#end
You can use this using below
-(void)getJsonCalling
{
#try {
NSString *strParameter=[NSString stringWithFormat:#"param1=%#&param2=%#",param1,param2];
objJsonRest=[[JsonRest alloc]init];
[objJsonRest setDelegate:self];
[objJsonRest GetServiceCall:DOMAIN Paraqmeter:strParameter];
[objJsonRest release];
}
#catch (NSException *exception) {
NSLog(#"Exception in %s %#",__FUNCTION__,exception);
}
}
- (void) JsonprocessSuccessful: (NSString *)receivedData
{
}
-(void) JsonprocessFail;
{
NSLog(#"FAIL");
}