Object-c / iOS:如何使用asynchronous从URL获取数据?
我的朋友看到我的代码,一部分是从URL获取plist数据
他告诉我不要使用同步,使用asynchronous
但我不知道如何以简单的方式做asynchronous
这是我在程序中使用的代码
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];
如何更改我的代码使用asynchronous获取数据?
非常感谢所有答复和答案:)
简答 :您可以使用
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
有关非正式委托协议,请参阅NSURLConnectionDelegate(所有方法都是可选的)
很长的回答 :
asynchronous下载数据并不像同步方法那么简单。 首先,您必须创build自己的数据容器,例如文件容器
//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]; }
当您连接到服务器时:
[NSURLConnection connectionWithRequest:myRequest delegate:self];
您必须使用asynchronous接收的数据填充容器:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:file]; [fileHandle seekToEndOfFile]; [fileHandle writeData:data]; [fileHandle closeFile]; }
您必须使用以下方式pipe理遇到的错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
如果你想捕获服务器响应:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
连接完成加载时处理:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
对于HTML源代码的asynchronous获取,我build议你使用AFNetworking
1)然后子类AFHTTPCLient,例如:
//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)请求asynchronousHTML源代码,把这个代码放在任何相关的部分
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];
- 在可重用表格单元格中使用NSCache和dispatch_async的正确方法是什么?
- 核心数据加载Swift后asynchronous刷新UITableView
- 检查来自Alamofire和Swift的多个asynchronous响应
- findObjectsInBackgroundWithBlock:从Parse获取数据,但数据只存在于块内
- Swift Serial Dispatch Block只有在委托之后才能完成
- Swift iOS:收到远程通知后,Closure不会在后台运行
- asynchronous获取Swift Xcode
- NSOperationQueue内部的NSOperation中的asynchronouscallback从来没有被调用过
- 何时在应用程序中调用completionHandler:performFetchWithCompletionHandler:当背景获取是asynchronous?