NSURLConnection Delegate not working properly in one situation - ios

I've read lots of posts regarding this problem but I couldn't get the callback delegate to work...
I've read that delegate cannot be in a background Thread or it won't get called. I think that this may be the issue... but... well let me put some code here to explain better my problem and see what you guys think.
in main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
#try {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:[object valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset)
{
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
//[data writeToFile:photoFile atomically:YES];//you can save image later
UIImage *image = [UIImage imageWithData:data];
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.5f;
int maxFileSize = 1280*720; //ou usar 40960 = 40MB ?
NSData *imageData = UIImageJPEGRepresentation(image, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(image, compression);
}
NSString *guid = [self.idMediasAvailable lastObject];
//NSString *guid = [[NSUUID UUID] UUIDString];
NSString *boundary = #"-endUploadBoundary-";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[client addBlobToContainer:[container objectAtIndex:self.mycontainerIndex] blobName:[NSString stringWithFormat:#"%#.jpg", guid] contentData:imageData contentType:contentType ];
[uploadedMediaID setObject:object forKey:guid];
[confirmMedias addObject:guid];
[listUploadedMedias addObject:object];
[self.idMediasAvailable removeLastObject];
// [allUploadedLock lock];
// [allUploadedLock unlockWithCondition:0];
}
failureBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
[allUploadedLock lock];
[allUploadedLock unlockWithCondition:0];
}];
}
#catch (NSException *exception) {
NSLog(#"Error uploadMedia: %#",[object valueForKey:UIImagePickerControllerReferenceURL]);
}
});
[allUploadedLock lockWhenCondition:0];
[allUploadedLock unlock];
this is the addToBlobContainer selector:
- (void)addBlobToContainer:(BlobContainer *)container blobName:(NSString *)blobName contentData:(NSData *)contentData contentType:(NSString*)contentType withBlock:(void (^)(NSError*))block
{
CloudURLRequest* request = nil;
if(_credential.usesProxy)
{
request = [_credential authenticatedRequestWithEndpoint:#"/SharedAccessSignatureService/blob" forStorageType:#"blob" httpMethod:#"PUT" contentData:contentData contentType:contentType, #"x-ms-blob-type", #"BlockBlob", nil];
}
else
{
NSString* containerName = [container.name lowercaseString];
NSString* endpoint = [NSString stringWithFormat:#"/%#/%#", [containerName URLEncode], [blobName URLEncode]];
request = [_credential authenticatedRequestWithEndpoint:endpoint forStorageType:#"blob" httpMethod:#"PUT" contentData:contentData contentType:contentType, #"x-ms-blob-type", #"BlockBlob", nil];
}
[request fetchNoResponseWithBlock:^(NSError* error)
{
if(error)
{
if(block)
{
block(error);
}
else if([(NSObject*)_delegate respondsToSelector:#selector(storageClient:didFailRequest:withError:)])
{
[_delegate storageClient:self didFailRequest:request withError:error];
}
return;
}
if(block)
{
block(nil);
}
else if([(NSObject*)_delegate respondsToSelector:#selector(storageClient:didAddBlobToContainer:blobName:)])
{
[_delegate storageClient:self didAddBlobToContainer:container blobName:blobName];
}
}];
}
no breakpoint is hit inside the block [request fetchNoResponseWithBlock:ˆ(NSError *error) ...];
and this is the fetchNoResponseWithBlock:ˆ selector:
- (void) fetchNoResponseWithBlock:(noResponseBlock)block {
_noResponseBlock = [block copy];
[NSURLConnection connectionWithRequest:self delegate:self];
}
and in this same file I have the delegate selectors
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
and none of these are hit as well... btw the interface declaration is #interface CloudURLRequest : NSMutableURLRequest
Ok now the strange thing is that the breakpoints inside the delegate selectors
are hit when the page is opened and another request is made to get the Blob Containers... but when I try to send a file the file is sent and there is no callback! (I manually check the blob and it uploaded successfully)
I think that when I do this:
[assetLibrary assetForURL:[object valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {
is this block running on a background thread by any chance? or Any suggestions?
I do need the callback to work because I have to unlock a NSLock only when the file completes the upload.
Thanks a lot in advance!

Related

How to check when connectionDidFinishLoading finishes

I have set up a simple Objective-C class in my iOS app which has one simple task, to download a JSON file, parse it and then pass back a NSString which contains a variable parsed from the downloaded JSON file.
The problem I have is that I am calling this class from another class and this all works great however I need to pass back the NSString to the class from which I am calling it from.
The problem is that the method passes back the empty NSString BEFORE connectionDidFinishLoading happens.... And so the NSString never gets assigned a string......
I have setup a while loop in my method but it doesn't really work.....
here is my code:
-(NSString *)get_user_icon:(NSString *)YT_ID {
// Set BOOL to 0 for initial setup.
icon_check = 0;
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
dispatch_queue_t downloadQueue = dispatch_queue_create("Icon downloader YouTube", NULL);
dispatch_async(downloadQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLConnection *theConnection_YT = [[NSURLConnection alloc] initWithRequest:theRequest_YT delegate:self];
if (theConnection_YT) {
YT_JSON_FEED = [[NSMutableData alloc] init];
NSLog(#"Respoce happening...");
}
else {
NSLog(#"failed");
}
});
});
while (icon_check == 0) {
NSLog(#"Wait");
}
return icon_url;
}
/// Data loading ///
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[YT_JSON_FEED setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[YT_JSON_FEED appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *myError = nil;
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:YT_JSON_FEED options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
icon_check = 1;
}
For a synchronous request (blocking until there is something to return), use NSURLConnection's sendSynchronousRequest:returningResponse:error: instead. Like so:
-(NSString *)get_user_icon:(NSString *)YT_ID {
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:theRequest_YT returningResponse:&response error:&error];
//Check response and error for possible errors here.
//If no errors.
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
return icon_url;
}
However this is not recommended. You need to change your API to be asynchronous. Either delegate-based, but more preferably, using block-based API.

When changing view controllers NSURLConnection delegate not updating the progress bar

I am performing a download through NSURLConnection class and updating a progress bar view according to the received bytes in the NSURLConnection delegate connection didReceiveData.
Everything is working fine when I am on the page where downloading is happening but when I am going to some other view controller and coming back to my downloading page, the connection delegate functions are being called while transition of page but coming back does not upgrade the progress bar.
The code I am using is:
- (IBAction)download:(id)sender {
_currentURL = [NSString stringWithFormat:#"url_to_download"];
NSURL *url =[NSURL URLWithString:_currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
_receivedData = [[NSMutableData alloc]initWithLength:0];
connection2 = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"THE STATUS CODE IS %d",[httpResponse statusCode]);
statuscode = [httpResponse statusCode];
NSLog(#"into didReceiveResponse");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[_receivedData setLength:0];
expectedBytes = [response expectedContentLength];
NSLog(#"EXPECTED BYTES:%ld",expectedBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into did receivedata");
[_receivedData appendData:data];
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
[self.progress setProgress:progressive];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication]delegate];
NSLog(#"into didfailwitherror");
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"connection failed");
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.setting.enabled = YES;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"DOCUMENT DIRECTORY :%#",documentsDirectory);
_imagePath = [documentsDirectory stringByAppendingPathComponent:_fullPath];
NSLog(#"iamge path:%#",_imagePath);
NSLog(#"succeeded");
[UIApplication sharedApplication].networkActivityIndicatorVisible= NO;
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
// flag= [_receivedData writeToFile:imagePath atomically:NO];
if([_receivedData writeToFile:_imagePath atomically:YES])
{
NSLog(#"write successfull");
app.dl_status = 0;
[HUD hide:YES];
[HUD removeFromSuperview];
HUD = nil;
[self completedDownloadHUD];
[self.download setBackgroundImage:[UIImage imageNamed:#"download.png"] forState:UIControlStateNormal];
}
else{
app.dl_status = 0;
NSLog(#"write failed");
[HUD hide:YES];
[self errorDownloadHUD];
}
NSString *imagePathExtension;
imagePathExtension = [_imagePath pathExtension];
if([imagePathExtension isEqual:#"jpg"])
{
NSLog(#"imagepathextension is jpg");
UIImage *img =[UIImage imageWithContentsOfFile:_imagePath];
UIImageWriteToSavedPhotosAlbum(img, self, #selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
else if([imagePathExtension isEqual:#"mov"])
{
NSLog(#"imagepathextension is mp4");
UISaveVideoAtPathToSavedPhotosAlbum(_imagePath, nil, nil, nil);
}
}
Please tell me how i can retain the value of progress bar while coming back to page and update it.
Change your delegate to this then update the question. I suspect you will find something gets hit with the asserts:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"into didReceiveData");
[_receivedData appendData:data];
assert(_receivedData); // it exists
assert([_receivedData length]); // it also has some data in it
self.setting.enabled = NO;
float progressive = (float)[_receivedData length] / (float)expectedBytes;
assert(expectedBytes > 0);
assert(progressive > 0 && progressive <= 1);
assert(self.progress);
assert(!self.progress.hidden);
assert(!self.progress.alpha > 0.5);
assert(self.progress.window);
[self.progress setProgress:progressive];
}
If you don't get any asserts, you still are getting delegate messages, and the progress bar is not visible (or not moving) then log the value of progressive and/or the progress bar frame.

How to waiting asynchronous NSURLConnection response

I am trying to fill a UITableView by fetching an URL. To avoid freeze UI I using dispatch_async(dispatch_queue_t queue, ^(void)block) making asynchronous fetching.
In the asynchronous block using NSRunLoop to waiting response.
Here's my fetching code:
- (BOOL)isFinished {
return _finished;
}
- (void)startReceive {
NSURLRequest* request = [NSURLRequest requestWithURL:self.baseURL];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
assert(self.connection);
}
- (void)stopReceiveWithStatus:(NSString*)statusCode {
if (self.connection) {
[self.connection cancel];
self.connection = nil;
}
self.finished = YES;
NSLog(#"Stop Receive with status code %#", statusCode);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
assert(connection == self.connection);
NSHTTPURLResponse* httpResponse = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
httpResponse = (NSHTTPURLResponse*) response;
if (httpResponse.statusCode != 409) {
// I need 409 to fetch some data
[self stopReceiveWithStatus:[NSString stringWithFormat:#"HTTP error %2d", httpResponse.statusCode]];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
assert(connection == self.connection);
self.sessionID = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
assert(connection == self.connection);
[self stopReceiveWithStatus:#"Connection failed"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
assert(connection == self.connection);
[self stopReceiveWithStatus:nil];
}
UITableViewController:
// refreshControl handler
- (IBAction)refresh {
[self startRefreshingAnimation];
dispatch_queue_t loaderQ = dispatch_queue_create("loading transmission data", NULL);
dispatch_async(loaderQ, ^{
[self foo];
while(!self.t.finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self endRefreshingAnimation]; // end
});
});
}
- (void)foo {
NSLog(#"session id: %#", self.t.sessionID);
}
That sessionID will be filled when HTTP request has done. Now the problem is I can not get the sessionID when first call because the first time it not be filled and second time it works good. How can I get it when first call?
I'm new to iOS. If you have a better solution to solve this problem please tell me, thanks.
There is a good framework, don't waste your time.
https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking
Upd.
You can do your request like:
NSURL *url = self.baseURL;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
You should use an third-party library to handle network connections, such as STHTTPRequest:
STHTTPRequest *r = [STHTTPRequest requestWithURLString:#"http://www.apple.com"];
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
// ...
};
r.errorBlock = ^(NSError *error) {
// ...
};
[r startAsynchronous];

ASIHTTPRequest set Download Destination Path failing

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]);
}

Show Activity Indicator when fetching JSON data

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];
}

Resources