我从网址中检索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???
}
答案 0 :(得分:0)
随着数据以递增方式加载,将重复调用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];
}