AFNetworking setImageWithURLRequest 不更新 UIImageView

AFNetworking setImageWithURLRequest not updating UIImageView

我正在使用 setImageWithURLRequest:placeholderImage:success:failure 从 URL 下载图像并且图像下载工作正常。我遇到的问题是,当我将下载的图像设置为 UIIMageView 时,除了占位符被删除外,什么也没有显示。

我的代码如下:

__weak UIImageView *userCardImageView;


AFImageResponseSerializer *serializer = [[AFImageResponseSerializer alloc] init];
serializer.acceptableContentTypes = [serializer.acceptableContentTypes setByAddingObject:@"image/png"];
self.userCardImageView.imageResponseSerializer = serializer;

[self.userCardImageView setImageWithURLRequest:urlRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

        [userCardImageView setImage:image];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {

        if (error)
        {
            NSLog(@"Error:   %@", error);
            NSLog(@"Error response:     %@", response);
        }

    }];

URL 是正确的,因为当我将它复制并粘贴到浏览器中时,我得到了我的图像。

有人可以告诉我如何让我的代码工作以更新 URL 吗?我将 UIImageView 分配给弱 属性 是否正确?我这样做是因为使用 self 或强变量可能会导致保留周期。

实际上你没有正确地将下载的图像分配给图像视图。[userCardImageView setImage:[UIImage imageWithData:userCardImageData]];,我们不需要从这个变量userCardImageData分配图像,试试这个代码

[self.userCardImageView setImageWithURLRequest:urlRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [userCardImageView setImage:image]; //set image in main thread , we got downloaded image as parameter in block
    });


} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {

    if (error)
    {
        NSLog(@"Error:   %@", error);
        NSLog(@"Error response:     %@", response);
    }

}];

希望对您有所帮助

看来你应该实施这条线

[userCardImageView setImage:image];    

而不是

[userCardImageView setImage:[UIImage imageWithData:userCardImageData]];

在你的成功块

PS:如果你想在self.userCardImageView中设置图像,你宁愿声明一个弱控制器而不是一个弱UIImageView引用。像

__weak __typeof(&*self)weakSelf = self    

应该够了:

[self.userCardImageView setImageWithURL:url];