开发者

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 sendSynchronousReques开发者_StackOverflowt: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 : )


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


For asynchronous fetch of HTML source code, I recommend you to use AFNetworking

1) Then subclass AFHTTPCLient, for example:

//WebClientHelper.h
#import "AFHTTPClient.h"

@interface WebClientHelper : AFHTTPClient{

}

+(WebClientHelper *)sharedClient;

@end

//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"

NSString *const gWebBaseURL = @"http://dummyBaseURL.com/";


@implementation WebClientHelper

+(WebClientHelper *)sharedClient
{
    static WebClientHelper * _sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    return self;
}
@end

2) Request asynchronously HTML source code, put this code in any relevant part

NSString *testNewsURL = @"http://whatever.com";
    NSURL *url = [NSURL URLWithString:testNewsURL];
    NSURLRequest *request  = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operationHttp =
    [[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
         NSLog(@"Response: %@", szResponse );
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Operation Error: %@", error.localizedDescription);
     }];

    [[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜