我试图异步实现加载图像。
NSURL *url = [NSURL URLWithString:_posterImg];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage *getImg = [[UIImage alloc] initWithData:data];
// do whatever you want with image
}
}];
但是当我输入此代码时,getImg将收到警告" Unused Variable"。我检查了#34;响应","数据"并且"错误",它看起来都很好,但getImg是NIL。是我写错了什么?感谢。
答案 0 :(得分:1)
受影响的变量为response
。虽然您使用数据和错误,但响应仅被声明为参数,但在您的完成处理程序中没有使用!
NSURL *url = [NSURL URLWithString:_posterImg];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
NSString *errorMsg = nil;
UIImage *getImg = nil;
if (!error){
getImg = [[UIImage alloc] initWithData:data];
}
else
{
errorMsg = [NSString stringWithFormat:@"Failed to load image. Error Message: %@", [error localizedString]];
}
[self handleImageRequestWithResponse:response image:getImg andErrorMessage:errorMsg];
}];
// Image hasn't load yet here since the request is asynchronously!
//if(getImg != nil && errorMsg == nil)
// NSLog(@"Image is available!");
//else
// NSLog(@"Loading the image asynchronously failed! %@", errorMsg);
// In addition now provide the following method.
- (void) handleImageRequestWithResponse:(NSURLResponse*)response image:(UIImage*)img andErrorMessage:(NSString*)err
{
if(img!= nil && err == nil)
NSLog(@"Image is available!");
else
NSLog(@"Loading the image asynchronously failed! %@", err);
// Handle image
};
编辑:我的不好!由于代码以异步方式执行,因此当您按之前检查时,getImg当然为零
编辑:
使用NSData dataWithContentsOfURL
是同步的,即。如果在主线程上执行,则应用程序被阻止。
请参阅此官方文档:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/clm/NSData/dataWithContentsOfURL:
最重要的是:
重要提示:请勿使用此同步方法来请求基于网络的网址。对于基于网络的URL,此方法可以在慢速网络上阻止当前线程持续数十秒,从而导致用户体验不佳,而在iOS中,可能会导致应用程序被终止。
在处理/准备好所请求的原始数据后调用completionHandler和处理程序方法对您的表现更好,并且不违反官方建议!