Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-c/iOS :How to use ASynchronous to get a data from URL?

My friend saw my code, a part is get a plist data from URL

And he told me not to use Synchronous,Use ASynchronous

But I don't know how to do ASynchronous in simple way

This is the code I use in my program

NSURL *theURL =  [[NSURL alloc]initWithString:@"http://someurllink.php" ];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:theURL
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil]; 
NSString *listFile = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];   
self.plist = [listFile propertyList];
[self.tableView reloadData];
[listFile autorelease];

How can I change my code use ASynchronous to get the data ?

Great thanks for all reply and answers : )

like image 897
Webber Lai Avatar asked Dec 22 '10 02:12

Webber Lai


1 Answers

Short answer: You can use

+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;

See NSURLConnectionDelegate for the informal delegate protocol (all methods are optional)

Long answer:

Downloading data asynchronously is not as straightforward as the synchronous method. First you have to create your own data container e.g. a file container

//under documents folder/temp.xml
file = [[SomeUtils getDocumentsDirectory] stringByAppendingPathComponent:@"temp.xml"]
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:file]) {
  [fileManager createFileAtPath:file contents:nil attributes:nil];
}

When you connect to server:

[NSURLConnection connectionWithRequest:myRequest delegate:self];

You have to fill the container with the data you receive asynchronously:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:file];
  [fileHandle seekToEndOfFile];
  [fileHandle writeData:data];
  [fileHandle closeFile];
}

You have to manage errors encountered using:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

If you want to capture the server response:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response

Handle when connection finished loading:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
like image 132
Manny Avatar answered Oct 18 '22 09:10

Manny