iOS:UIImage 不可分配(FBSDKGraphRequest)

Posted

技术标签:

【中文标题】iOS:UIImage 不可分配(FBSDKGraphRequest)【英文标题】:iOS: UIImage is not assignable (FBSDKGraphRequest) 【发布时间】:2015-12-26 22:01:14 【问题描述】:

我正在构建一个用于检索用户个人资料图片的函数。我正在使用 facebook 的 FBSDKGraphRequest 但一旦我尝试使用检索到的数据将其分配到图片中,就会收到一个我不明白的错误:Variable is not assignable (missing _block type specifier)

我的功能如下:

- (UIImage *)getProfilePicture: (NSString *)ID


    FBSDKGraphRequest *requestFriends = [[FBSDKGraphRequest alloc] initWithGraphpath:@"me/friends" parameters:@@"fields": @"name"];
    FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];

    //[connection addRequest:requestFriends completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)

    UIImage* profilePic;


    NSString* requestPath = @"me/?fields=name,location,gender,birthday,relationship_status,picture,email,id";
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@@"fields": @"picture"];
    [connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError* error)
    
        NSDictionary* data = (NSDictionary *)result;
        NSDictionary* picture = [data objectForKey:@"picture"];
        NSDictionary* pictureData = [picture objectForKey:@"data"];
        NSString* pictureURL = [pictureData objectForKey:@"url"];
        profilePic = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:pictureURL]]];
    ];

    return profilePic;

【问题讨论】:

【参考方案1】:

错误是告诉你在profilePic 声明之前添加__block

__block UIImage* profilePic;

但是,它不会解决您的问题。

关键是你的 -(UIImage *)getProfilePicture: (NSString *)ID 方法是同步的,而FBSDKGraphRequest 调用(带有完成块)是异步的。

我可能会建议您在您的方法中添加一个 UIImage 回调,或者在 Facebook SDK 调用完成块时使用委托模式返回图像。

另一种解决方案,但不太实用:使调用完全同步,您的方法将等到 FBSDKGraphRequest 完成然后返回 UIImage,但它会阻塞该方法正在运行的线程(可能是主一)。

【讨论】:

添加__block 修复了错误,但是正如您所说,该功能不起作用。如何将 UIImage 回调添加到您建议的方法中? 例如定义typedef void (^ImageCompletionHandler)(UIImage *img); 并将ImageCompletionHandler 作为参数传递给getProfilePicture 方法。你可以在 1 级以上面临同样的问题,但我认为将图像分配给 UIImageView 或任何你需要的都可以。

以上是关于iOS:UIImage 不可分配(FBSDKGraphRequest)的主要内容,如果未能解决你的问题,请参考以下文章

iOS 13`withTintColor`不服从我分配的颜色

iOS 9.3 中的 UIImageView 如何渲染 UIImage?

UIImage知识点汇总

如何分配“字符串”类型的值?输入“UIImage?”

当动画 UIImage 被分配两次时,UITableViewCell 中的 UIImageView 没有动画

将 UIImage 分配给 Collection View Cell