我已更改旧的NSthread
,因为无法从后台线程更新UI。现在我正在使用dispatch_async
。
问题是当第二次执行此代码时,在ApplicationDidBecomeActive中(当用户隐藏并再次显示应用程序时)从不退出,同时保持无限循环。
在这里,我展示了有关dispatch_async的新代码,NSURLConnection
代码始终有效,最后恢复......我不认为问题存在
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// first connection to the server through NSURLConnection, downloading a json list
[wsDataVideos getVideosData:URL_WS_VIDEOS];
dispatch_queue_t secondDownloadQueue = dispatch_queue_create("name",NULL);
dispatch_async(secondDownloadQueue, ^{
// wait for wsDataVideos has finished. IT SEEMS THIS COLLAPSES CPU ¿?
while (wsDataVideos.imported==NO) {}
// If are there new videos begins sincronous and slower download:
if ....{
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI: inform user begins download
[menuViewController.badgeVideos setBadgeVideosText:@"Downloading..."];
});
// Download videos (sincro)
dispatch_async(dispatch_get_main_queue(), ^{
// informs user is completed
[menuViewController.badgeVideos setBadgeVideosText:@"Downloaded"];
});
}
});
}
第一个连接(json),比我在那时等待:
-(void)getVideosData:(NSString *)url_ws{
NSLog(@"Get videos data1 ");
if (wsData){
[wsData setLength:0];
}
else{
wsData=[[NSMutableData alloc] init];
}
NSURLRequest *reqCat=[NSURLRequest requestWithURL:[NSURL URLWithString:url_ws] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *conCat=[[NSURLConnection alloc] initWithRequest:reqCat delegate:self];
}
用他们的方法:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
...
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[wsData appendData:data];
}
...
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
...
有什么想法吗?再次感谢。
答案 0 :(得分:0)
如果我把代码放在{}它可行的情况下,但我认为这是奇怪的事情。糟糕,糟糕的代码,不是吗? 也许更好的解决方案就像dispatch_group_wait()?
// wait for wsDataVideos has finished. IT SEEMS THIS COLLAPSES CPU ¿?
while (wsDataVideos.imported==NO) {
sleep(1)
}