更新图像并将其保存在字典中

时间:2016-11-03 07:43:24

标签: ios objective-c iphone uiimageview

我在ViewController A上从字典中获取图像作为url并且我已将该字典传递给ViewController BI希望如果用户更新了图像,那么它会显示更新的图像,否则它会显示上一个图像,我正在执行以下操作它的代码。亲自检查并告诉它为什么不能按预期工作,并且只在每种情况下显示前一个图像。

-(void)showUserImage:(NSURL*)imgUrl
{

    [ConnectionManager setSharedCacheForImages];


    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:imgUrl];

    NSURLSession *session = [ConnectionManager prepareSessionForRequest];

    NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    if (cachedResponse.data) {

        UIImage *downloadedImage = [UIImage imageWithData:cachedResponse.data];

        dispatch_async(dispatch_get_main_queue(), ^{
            _profileImageView.image = downloadedImage;
        });
    } else {
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
            if(res.statusCode == 200){

                dispatch_async(dispatch_get_main_queue(), ^{

                    _profileImageView.image = [UIImage imageWithData:data];

                });

            }
        }];
        [task resume];
    }


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
        if(_profileImageView.image == [_detailsDictionary valueForKey:@"ProfilePictureUrl"]) {
            NSLog(@"Th url of image is %@",[_detailsDictionary valueForKey:@"ProfilePictureUrl"]);
        }
        else {
            _profileImageView.image = image;

            UIImage *updatedImage =  _profileImageView.image;
            NSData *imageData = UIImageJPEGRepresentation(updatedImage, 100);

            NSString *strEncoded = [imageData base64EncodedStringWithOptions:0];
            [_detailsDictionary setObject:strEncoded  forKey:@"ProfilePictureUrl"];

            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }

2 个答案:

答案 0 :(得分:1)

@Dirtydanee,他是绝对正确的,你在Url和UIImage之间进行不兼容的比较。所以请使用以下代码更正此内容。

NSData *data1 = UIImagePNGRepresentation(previousImage);
NSData *data2 = UIImagePNGRepresentation(currentImage);

if([data1 isEqualToData:data2]) {
  //Do something
} else {
  //Do something
}

将图像转换为NSData并比较数据。 如果您想逐位比较请查看以下链接:

Generate hash from UIImage

答案 1 :(得分:0)

问题似乎在于这一行:

if(_profileImageView.image == [_detailsDictionary valueForKey:@"ProfilePictureUrl"]) {

您正在尝试将来自字典的_profileImageView.imageUIImage[_detailsDictionary valueForKey:@"ProfilePictureUrl"]NSURL实例进行比较。

您可以做的是检查所选图像和profileImage是否相同。

if(_profileImageView.image == image) {
// etc..

要清除以前缓存的图片,只需致电:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

希望这有帮助!