我正在寻找有关获取一组 Facebook 朋友(其 Facebook ID 存储在数组中)的个人资料图片的最佳方法的清晰完整说明。在我的应用程序的其他地方,我使用以下代码来获取当前用户的图像:
...
...
// Create request for user's Facebook data
FBRequest *request = [FBRequest requestForMe];
// Send request to Facebook
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(@"no fb error");
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
// Download the user's facebook profile picture
self.imageData = [[NSMutableData alloc] init]; // the data will be loaded in here
// URL should point to https://graph.facebook.com/{facebookId}/picture?type=large&return_ssl_resources=1
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=square&return_ssl_resources=1", userData[@"id"]]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:pictureURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:2.0f];
// Run network request asynchronously
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!urlConnection) {
NSLog(@"Failed to download picture");
}
}
}];
}
// Called every time a chunk of the data is received
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.imageData appendData:data]; // Build the image
}
// Called when the entire image is finished downloading
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[[PFUser currentUser] setObject:self.imageData forKey:@"image"];
[[PFUser currentUser] saveInBackground];
}
这种方法似乎具有在后台下载数据的优势,但似乎将其作为循环的一部分来实现可能会很棘手,for
在该循环中,我循环遍历一组用户的 Facebook 朋友以获取他们的个人资料图片,因为它调用多个委托方法,然后我必须跟踪委托方法中接收到的朋友的图像数据。
考虑到遍历这些朋友的 for 循环将在主线程上执行并在数据收集完成之前的迭代之前完成(我相信)?
我想解决这个问题的一种方法是在后台线程中执行整个 for 循环,在该线程中我不会迭代到下一个朋友,直到当前朋友收集所有数据。然后我就不需要使用NSURLConnection
异步调用了。这可能会大大简化代码。这会是一个好的解决方案吗?如果是,我将如何设置这样的后台进程?
或者您会推荐什么其他解决方案?