所以我正在将一些数据从服务器下载到我的 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
就是这样。