Hey guyz I have this issue regarding the NSUrlConnection where I initiate a request like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:URL_PACKAGE,2]]];
Communication *comm = [[Communication alloc] initWithUrlRequest:request];
comm.request_name = request_name;
comm.delegate = self;
[comm startAsynchronous];
[request release];
and then the response getting code is fine but as you can see I have created a communication class to make the connection and when I request with difference web services it
- (Communication *) initWithUrlRequest:(NSMutableURLRequest *)url_request {
self.request = url_request;
return self;
}
-(void)dealloc {
[super dealloc];
}
- (void) startAsynchronous {
responseData = [[NSMutableData data] retain];
NSLog(#"%#",[request URL]);
downloadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
[responseData setLength:0];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveResponse:RequestName:)] ) {
[self.delegate communication:self didReceiveResponse:response RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[responseData appendData:data];
if ( [[self delegate] respondsToSelector:#selector(communication:didReceiveData:RequestName:)] ) {
[self.delegate communication:self didReceiveData:data RequestName:self.request_name];
}
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
[self.delegate communication:self didFailWithError:error RequestName:self.request_name];
NSLog(#"%#", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
[responseData release];
responseString = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"+" withString:#" "];
responseString = [responseString stringByReplacingOccurrencesOfString:#"null" withString:#"\"\""];
[self.delegate communication:self didFinishWithString:responseString RequestName:self.request_name];
}
The error is
2013-07-30 13:55:46.994 Ipad Qld[3982:c07] *** -[Requests respondsToSelector:]: message sent to deallocated instance 0xa16b310
Related
Im new to ios i have a doubt that i want to send data to server and receive response in same method
i have a class name
profile.m and i want to send data to service class and receive response in profile class
Profile.m:
NSString *parameter = [NSString stringWithFormat:#"%#&access_token=%#&lksite=social&lkmenu=profile&lktype=view&displayedname=%#&displayid=%#", baseUrl, accessToken, userName,userId];
Service *service = [[Service alloc]init];
[service sendDataToServer:#"POST" andUrl:parameter andUrl:baseUrl];
Service.m
-(void) sendDataToServer:(NSString *) method andUrl:(NSString *) getUrl andUrl:(NSString *)baseUrl{
NSMutableData *jsondata;
Session *ses =[[Session alloc]init];
accessToken = [ses getAccessToken];
NSLog(#"Access Token---> %#",accessToken);
NSString *baseUrl1 = [NSString baseUrl];
if([method isEqualToString:#"GET"]){
NSString *urlStr = [NSString stringWithFormat: #"%#&access_token=%#",getUrl,accessToken];
url = [NSURL URLWithString: urlStr];
urlRequest= [NSMutableURLRequest requestWithURL:url];
urlRequest.HTTPMethod=method;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if( connection )
{
urlMutable = [NSMutableData new];
}
}else{
NSData *parameterData = [getUrl dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: baseUrl1];
urlRequest=[NSMutableURLRequest requestWithURL:url];
urlRequest.HTTPBody=parameterData;
urlRequest.HTTPMethod=method;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if( connection )
{
urlMutable = [NSMutableData new];
}
}}
You can user NSLocalNotification to achieve your task.
There are three simple steps to use NSLocalNotification.
1) For this you can write your code in Profile.m file as:
- (void)viewDidLoad {
[super viewDidLoad];
Service *Service = [[Service alloc] init];
[Service sendDataToServer:(with your parameters here)];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(responceMethod:) name:#"WebServiceCall" object:nil];
}
2) in your Service.m class make a service call
-(void) sendDataToServer:(NSString *) method andUrl:(NSString *) getUrl andUrl:(NSString *)baseUrl{
NSMutableData *jsondata;
Session *ses =[[Session alloc]init];
accessToken = [ses getAccessToken];
NSLog(#"Access Token---> %#",accessToken);
NSString *baseUrl1 = [NSString baseUrl];
if([method isEqualToString:#"GET"]){
NSString *urlStr = [NSString stringWithFormat: #"%#&access_token=%#",getUrl,accessToken];
url = [NSURL URLWithString: urlStr];
urlRequest= [NSMutableURLRequest requestWithURL:url];
urlRequest.HTTPMethod=method;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if( connection )
{
urlMutable = [NSMutableData new];
}
}else{
NSData *parameterData = [getUrl dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: baseUrl1];
urlRequest=[NSMutableURLRequest requestWithURL:url];
urlRequest.HTTPBody=parameterData;
urlRequest.HTTPMethod=method;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if( connection )
{
urlMutable = [NSMutableData new];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
int errorCode = (int)httpResponse.statusCode;
NSLog(#"response is %d", errorCode);
[urlMutable setLength: 0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[urlMutable appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
id *response = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingAllowFragments error:&error];
[[NSNotificationCenter defaultCenter] postNotificationName:#"WebServiceCall" object:nil userInfo:response];
}
And finally
3) Implement your response parsing here in the method you have written in Profile.m file like:
-(void)responceMethod:(NSNotification *)notif{
NSDictionary *dict = [notif userInfo];
// Your response parsing.
}
Declare a block as :
typedef void (^completionBlock)(id responseObject , NSError *error);
And then add this block to your methods as :
- (void) performRequestWithCompletion:(completionBlock)block;
On invoking this method, will return you "responseObject" and "error". error nil in case of success
I created a class customDownload with the following methods:
-(NSString *) getTextFromLink: (PreliteRequest *) requestDetails
asyncConnection: (BOOL) isAsync
callbackMethod: (SEL) methodToExecute {
mainRequest = requestDetails;
NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc] init];
NSURLRequest *getRequest = [[NSURLRequest alloc] init];
NSURLConnection *connection;
NSURLResponse * response = nil;
NSError * error = nil;
if ([[requestDetails getType] isEqualToString:#"POST"]) {
[postRequest setURL:[NSURL URLWithString:[requestDetails getUrl]]];
[postRequest setHTTPMethod:[requestDetails getType]];
[postRequest setValue:[requestDetails getPostLenght] forHTTPHeaderField:#"Content-Length"];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setHTTPBody:[requestDetails getPostParameters]];
if (isAsync) {
tmpMethod = methodToExecute;
connection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
} else
downloadedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error];
} else {
getRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",[requestDetails getUrl],[requestDetails getGetParameters]]]];
if (isAsync) {
tmpMethod = methodToExecute;
connection = [[NSURLConnection alloc] initWithRequest:getRequest delegate:self];
} else
downloadedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:getRequest returningResponse:&response error:&error];
}
NSString *result=[[NSString alloc]initWithData:downloadedData encoding:NSUTF8StringEncoding];
return result;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[downloadedData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *tmpResult = [[NSString alloc]initWithData:downloadedData encoding:NSUTF8StringEncoding];
[self performSelector:tmpMethod withObject:tmpResult];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Connection error: %#",error);
}
In my view controller I declare the previous class and call the only method of that class getTextFromLink.
download = [[customDownload alloc] init];
[download getTextFromLink:request asyncConnection:YES callbackMethod:tmpSelector];
SEL tmpSelector = #selector(printResult:);
-(void) printResult:(NSString *) resultToPrint {
NSLog(#"Risultato: %#",resultToPrint);
}
I pass to getTextFromLink the tmpSelector as parameter because that is the method I would like to call as soon the getTextFromDownloadLink has finished its job.
Actually getTextFromLink execute an asynchronous connection.
What I'm trying to do is to execute something when the asyncronous connection finished to download datas.
I would like to create a callback custom class to do this.
Can anyone help me?
Rather than this selector model, generally people would use blocks for this. For example, define a typedef for your block:
typedef void(^PreliteRequestCompletionHandler)(NSString *string);
Since you're dealing with an asynchronous pattern, you might want to define a property which you can use to save this completion handler to call later:
#property (nonatomic, copy) PreliteRequestCompletionHandler completionHandler;
You can then change that selector parameter to be a block parameter:
-(NSString *) getTextFromLink: (PreliteRequest *) requestDetails
asyncConnection: (BOOL) isAsync
completionHandler: (PreliteRequestCompletionHandler)completionHandler {
self.completionHandler = completionHandler;
// do stuff
}
And then, when you want to call that completion block, you do something like:
NSString *result = ...;
if (self.completionHandler) {
self.completionHandler(result);
}
And then you can now use this new block parameter to your method:
download = [[customDownload alloc] init];
[download getTextFromLink:request asyncConnection:YES completionHandler:^(NSString *result) {
NSLog(#"Risultato: %#", result);
}];
I am trying to execute a async http request. but the call back log is not working. please analyze the code and suggest me the cause of this issue. I have seen the class examples in many places. But here i am calling it from a main function.
#interface HTTP : NSObject
#property (nonatomic,retain) NSMutableData *receivedData;
- (void) get : (NSString *) urlString;
#end
#implementation HTTP
#synthesize receivedData;
- (void)get: (NSString *)urlString {
NSLog ( #"GET: %#", urlString );
self.receivedData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 10
];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
[connection start];
}
- (void)connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Response recieved");
}
- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
NSLog(#"Data recieved");
NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[receivedData appendData:responseString];
}
#end
int main(const int c , char *arg[]){
HTTP *http = [[HTTP alloc] init];
[http get:#"http://www.apple.com"];
return 0;
}
Your program does not have a "run loop", therefore it terminates immediately after
[http get:#"http://www.apple.com"];
has returned, before any delegate functions are called. (Note that NSURLConnection works asynchronously.)
If this is for a stand-alone OS X application, you could to the following:
int main(const int c , char *arg[]){
HTTP *http = [[HTTP alloc] init];
[http get:#"http://www.apple.com"];
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
return 0;
}
where shouldKeepRunning is a (global) Boolean variable that is initially YES, and set to NO in
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
shouldKeepRunning = NO;
}
and also in connection:didFailWithError:. Or you add a Boolean property loading to your HTTP class.
If this is for an iOS application or a OS X Cocoa application, then you already have a run loop and don't have to add your own.
/*
Till the application finishes loading, the main thread is kept alive so that the delegate methods are called.
Hence the while loop below.
*/
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
Here is my working code.
#implementation HTTP
#synthesize receivedData,retStr,delegate;
- init {
if ((self = [super init])) {
receivedData = [[NSMutableData alloc] init];
}
return self;
}
- (void)get: (NSString *)urlString {
NSLog ( #"GET: %#", urlString );
self.receivedData = [[NSMutableData alloc] init];
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 10
];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if(!connection) {
NSLog(#"connection failed :(");
} else {
NSLog(#"connection succeeded :)");
}
}
- (void)post:(NSString*)urlString: (NSString*)body: (NSObject*) sender {
// POST
NSMutableString* requestURL = [[NSMutableString alloc] init];
[requestURL appendString:urlString];
NSMutableString* requestBody = [[NSMutableString alloc] initWithString:body];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];
NSString* requestBodyString = [NSString stringWithString:requestBody];
NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"text/html; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSURLConnection *postConn= [[NSURLConnection alloc] initWithRequest:request delegate:sender];
/*
Till the application finishes loading, the main thread is kept alive so that the delegate methods are called.
Hence the while loop below.
*/
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if(!postConn) {
NSLog(#"POST connection failed :(");
} else {
NSLog(#"POST connection succeeded :)");
}
}
// ====================
// Callbacks
// ====================
#pragma mark NSURLConnection delegate methods
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
NSLog(#"Connection received data, retain count");
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received response: %#", response);
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Received %lu bytes of data", [data length]);
[receivedData appendData:data];
NSLog(#"Received data is now %lu bytes", [receivedData length]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSRunAlertPanel(#"Error",[NSString stringWithFormat:#"Could not connect to server.Following error occured:\n\n%#", error], nil, nil, nil);
NSLog(#"Error receiving response: %#", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Once this method is invoked, "responseData" contains the complete result
NSLog(#"Succeeded! Received %lu bytes of data", [receivedData length]);
NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding] ;
retStr = [NSString stringWithString:dataStr];
finished =TRUE;
// [self returnDcString:dataStr];
// NSLog(#"%#",dataStr);
if ([delegate respondsToSelector:#selector(didFinishDownload:)]) {
NSLog(#"Calling the delegate");
//NSString* dataAsString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
// [delegate performSelector:#selector(didFinishDownload:) withObject: dataStr];
}
}
- (void)setDelegate:(id)val
{
delegate = val;
}
- (id)delegate
{
return delegate;
}
#end
I have a method which looks for a certain pdf, if it doesn't find it locally it uses ASIHTTPRequest to download it asynchronously. However the request always fails when the line:
[request setDownloadDestinationPath:currentDetailItem];
is uncommented, the request starts and the progress increases until 100% then the request failed block is executed.
These are the relevant NSLogs when the request fails:
2012-08-16 12:08:34.398 XXXX[1675:707] Request started with url :http://XXXX.com/gwas/sites/default/files/Responding%20to%20Severe%20Weather%20Events.pdf
filePath :/var/mobile/Applications/322C24CF-9664-403D-9CC5-13C396F39F84/Documents/Responding%20to%20Severe%20Weather%20Events.pdf
2012-08-16 12:08:39.018 XXXX[1675:707] Request failed:HTTP/1.1 200 OK
Here is the code for the method:
- (void)setDetailItem:(NSString *)newDetailItem {
NSArray *downloadPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *components = [newDetailItem componentsSeparatedByString:#"/"];
NSString *filePath = [[downloadPaths objectAtIndex:0] stringByAppendingFormat:#"/%#", [components lastObject]];
currentDetailItem = filePath;
if (![self fileExistsLocally:[components lastObject]]) {
//Download the file
[self displayProgressView];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:newDetailItem]];
[request setDownloadDestinationPath:currentDetailItem];
[request setDownloadProgressDelegate:progressBar];
[request setCompletionBlock:^
{
[self showPdf:currentDetailItem];
[self hideProgressView];
NSLog(#"%f, Request finished :%#", progressBar.progress, request.responseStatusMessage);
}];
[request setFailedBlock:^
{
NSLog(#"Request failed:%#", request.responseStatusMessage);
[self hideProgressView];
[SVProgressHUD showErrorWithStatus:#"Request failed"];
}];
[request startAsynchronous];
NSLog(#"Request started with url :%#\nfilePath :%#", newDetailItem, currentDetailItem);
}
else {
[self showPdf:currentDetailItem];
}
}
If I comment the line [request setDownloadDestinationPath:currentDetailItem]; out, the request is successful. Any ideas? thanks!
For anyone who is interested, I fixed the problem by swapping over to NSURLConnection, here's the code:
- (void)setDetailItem:(NSString *)newDetailItem {
NSArray *downloadPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *components = [newDetailItem componentsSeparatedByString:#"/"];
NSString *filePath = [[downloadPaths objectAtIndex:0] stringByAppendingFormat:#"/%#", [components lastObject]];
currentDetailItem = filePath;
if (![self fileExistsLocally:[components lastObject]]) {
[self displayProgressView];
data_ = [[NSMutableData alloc] init];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:newDetailItem] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
if (!connection) {
[SVProgressHUD showErrorWithStatus:#"Request failed"];
return;
}
else {
data_ = [[NSMutableData alloc] init];
}
}
else {
[self showPdf:currentDetailItem];
}
}
#pragma mark NSURLConnectionDelegate methods
- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
{
if ([response statusCode] == 200) {
currentDownloadSize = [response expectedContentLength];
}
[data_ setLength:0];
}
- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
[data_ appendData:data];
progressBar.progress = ((float) [data_ length] / (float) currentDownloadSize);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Save file locally
NSURL *url = [NSURL fileURLWithPath:currentDetailItem];
NSError *error = nil;
[data_ writeToURL:url options:0 error:&error];
if (error) {
NSLog(#"Write failed with error:%#", error);
}
else {
NSLog(#"Request successful");
[self showPdf:currentDetailItem];
}
[self hideProgressView];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[self hideProgressView];
[SVProgressHUD showErrorWithStatus:#"Request failed"];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}