我正在尝试通过从服务器下载图像来每1秒更新一次带有新图像的imageview。下载发生在后台线程中。下面显示的是代码
NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
target:self
selector:@selector(timerFired:)
userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
-(void)timerFired:(id)sender
{
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL
URLWithString:@"http://192.168.4.116:8080/RMC/ImageWithCommentData.jpg"]];
NSOperationQueue *queueTmp = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queueTmp completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
{
[self performSelectorOnMainThread:@selector(processImageData:) withObject:data waitUntilDone:TRUE modes:nil];
}
else if ([data length] == 0 && error == nil)
{
}
else if (error != nil)
{
}
}];
}
-(void)processImageData:(NSData*)imageData
{
NSLog(@"data downloaded");
[self.hmiImageView setImage:[UIImage imageWithData:imageData]];
}
我的图片正在下载。但是没有调用ProcessImageData方法。请帮我解决这个问题。
答案 0 :(得分:1)
问题是你是异步调用NSURLConnection:
[NSURLConnection sendAsynchronousRequest:request queue:queueTmp completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
所以在获得任何数据之前:if ([data length] > 0 && error == nil)
被调用。
所以数据长度保持为0,这就是为什么不调用你的方法。为了达到您的要求,您可以这样做:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
NSData *imageData = //download image here
UIImage* image = [[UIImage alloc] initWithData:imageData];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
//set image here
}
});
}
});