【问题标题】:UIImage returns null first time, until reloaded? [duplicate]UIImage 第一次返回null,直到重新加载? [复制]
【发布时间】:2015-08-31 14:21:35
【问题描述】:

我从 url 中检索 NSData,然后尝试将其设置为图像。 在控制台中它返回 null,但是当我请求数据并再次设置图像时,图像会加载吗?

为什么要加载两次才能加载?

这是我用来获取图片的两种方法。

-(void)getUserPicture {
//Grab and upload user profile picture
imageData = [[NSMutableData alloc] init]; // the image will be loaded in here
NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", userId];
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:3];

NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest
                                                                 delegate:self];
if (!urlConnection) NSLog(@"Failed to download picture");
}



-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    userPicture = [UIImage imageWithData:data];
    NSLog(@"%@",userPicture); //returns null in console first time, until reloaded???
}

【问题讨论】:

    标签: ios objective-c uiimage nsurl


    【解决方案1】:

    随着数据的增量加载,connection:didReceiveData: 方法被重复调用。您可能需要 connectionDidFinishLoading: 方法。

    顺便说一句,您可能仍需要connection:didReceiveData:,但您无需尝试创建图像,而是将新数据附加到缓冲区。然后在connectionDidFinishLoading: 方法中,获取缓冲区并创建图像。

    示例代码,但请根据需要添加错误处理:

    @property (strong, nonatomic) NSMutableData *data;
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        self.data = [NSMutableData data];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.data appendData:data];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        self.userPicture = [UIImage imageWithData:self.data];
    }
    

    【讨论】:

    • 我想到了,但我怎样才能从那个方法中得到NSData?它只在connection:didReceiveData: 中可用,对吗?
    • 我实现了你的方法,但我还在connectionDidFinishLoading 中添加了NSLog,它在运行时立即返回nil?为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多