所以我将一些数据从服务器下载到我的ios客户端。数据需要格式化,因此我使用NSNotification在数据完全下载时通知应用程序,完成后,我格式化数据然后在屏幕上显示。
所有这一切都很酷,但由于数据的大小,屏幕冻结。我想我应该使用GCD将数据下载推送到另一个线程,以便UI仍然响应。当我这样做时,我似乎没有下载任何数据。
我有一个使用getTops
下载数据的方法NSURLConnection
。最初,在我的viewDidLoad
我调用了这个方法并且它工作正常,但之后我就像这样使用GCD
dispatch_queue_t getItemsQ = dispatch_queue_create("get Items", NULL);
dispatch_async(getItemsQ, ^{
[self getTops];
});
它停止了工作。我知道它会转到getTops
,因为我可以在控制台中看到日志,但它永远不会到达-(void)connectionDidFinishLoading:(NSURLConnection *)connection
以下是我使用的代码:
-(void)getTops{
Keychain *keychain = [[Keychain alloc]init];
NSString *auth_token = [keychain getAuthToken];
NSLog(@"at getTops");
topimageArray = [[NSMutableArray alloc]init];
NSURLConnection *connection;
webData = [[NSMutableData alloc]init];
NSURL *url = [[NSURL alloc]initWithString:base];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL: url];
[request setValue:auth_token forHTTPHeaderField:@"X-AUTH-TOKEN"];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
// [connection start];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSLog(@"at getTops conn start");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"recieved response");
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(data) {
NSLog(@"Appending data");
[webData appendData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSArray *response= [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@"Tops full response::: %@",response);
theArray = [[NSArray alloc]initWithArray:response];
NSLog(@"DONE");
//Notify that the data is ready to be formated
[[NSNotificationCenter defaultCenter]postNotificationName:@"getTops" object:nil];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"error::::%@", error);
NSString *errormsg = error.localizedDescription;
UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"Error" message:errormsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertview show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
我想也许我应该删除[UIApplication sharedApplication].networkActivityIndicatorVisible
但是没有帮助
编辑::添加NSLogs以委派方法。 我得到的日志是
at getTops conn start
就是这样。
答案 0 :(得分:3)
最简单的方法是使用sendAsynchronousRequest:queue:completionHandler:。没有代理是必要的,只需将connectionDidFinishLoading中的代码放在完成块中。
加载URL请求的数据,并在请求完成或失败时在操作队列上执行处理程序块。
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
< your code >
}];