Object-c/iOS: как использовать ASynchronous для получения данных из URL-адреса?
Мой друг увидел мой код, часть получает данные plist из URL
И он сказал мне не использовать синхронный, использовать асинхронный
Но я не знаю, как сделать 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 для получения данных?
Большое спасибо за ответы и ответы:)
Ответы
Ответ 1
Короткий ответ. Вы можете использовать
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
См. NSURLConnectionDelegate для неофициального протокола делегатов (все методы не являются обязательными)
Длинный ответ:
Загрузка данных асинхронно не так проста, как синхронный метод. Сначала вы должны создать свой собственный контейнер данных, например. контейнер файлов
//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];
Вы должны заполнить контейнер данными, которые вы получаете асинхронно:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:file];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
Вам необходимо устранить ошибки, возникшие с помощью:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
Если вы хотите захватить ответ сервера:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
Обрабатывать при завершении загрузки соединения:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
Ответ 2
Для асинхронной выборки исходного кода HTML я рекомендую использовать 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) Запросите асинхронно исходный код HTML, поместите этот код в любую соответствующую часть
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];