使用UIImagePickerController

时间:2018-03-18 06:14:14

标签: ios objective-c uiimageview uiimagepickercontroller

我使用uiimagepickercontroller有一个有趣的小问题,并想知道是否有人对可能发生的事情有任何见解。用户可以使用相机拍照或从照片库中选择,直到奶牛连续多次回家。我的问题在于允许用户恢复到应用随附的原始图像。这是流程:

  1. 用户转到显示图像缩略图的tableview。
  2. 用户导航到详细视图,该视图显示更大的图像视图。
  3. 用户可以点击详细视图中的图像以显示自定义警报控制器,其中包括以下选项:a)使用相机拍照,b)使用图库中的图片,或c)恢复原始图像
  4. 用户可选择“a”选项或选项“b”来拍照或使用照片库中的照片。如果他们立即改变主意使用其中一种选择,并希望重新使用原始图像,则没有任何反应!他们可以拍摄另一张照片或立即选择其他照片,但无法立即恢复原始图像。
  5. 恢复原始图像当应用程序关闭然后再次打开时,它可以正常工作。有时,如果您在应用程序中导航到其他视图,然后返回到他们刚刚添加了自己的图像的详细视图,它将起作用。为何延迟?我已经搜索了两个星期,但没有发现任何类似于我的问题或任何有任何帮助的解决方案(比如重新加载图像所在的标题视图)。有什么想法吗?

    此外,我已经弄清楚如何使用文档将图像保存到iCloud,但无法弄清楚如何检索它们,因此没有代码。这是完全不同的问题。即使没有该代码,似乎也会发生同样的事情。

    感谢您花时间看看这个!

    以下是一些代码:

        -(void)bookImageTapped:(UIGestureRecognizer *)gesture
    {
        URBAlertView *changeImageAlertView = [[URBAlertView alloc] initWithTitle:@"Add A New Book Cover Image" message:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Use Camera", @"Open Gallery", @"Use Original Photo", nil];
        [changeImageAlertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
    
            [self checkPermission];
    
            if (PHAuthorizationStatusAuthorized)
            {
                if(buttonIndex == 0)
                {
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
                            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                            pickerController.delegate = self;
                            pickerController.allowsEditing = NO;
                            pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
                            [self presentViewController:pickerController animated:YES completion:nil];
                        }];
    
                        [alertView hide];
                    }
                    else
                    {
                        NSLog(@"Camera not available");
                        [alertView hide];
                    }
                }
                else if (buttonIndex == 1)
                {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
                        pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        pickerController.delegate = self;
                        pickerController.allowsEditing = NO;
                        pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                        [self presentViewController:pickerController animated:YES completion:nil];
                    }];
                    [alertView hide];
                }
                else if (buttonIndex == 2)
                {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [self restoreOriginalPhoto];
                    }];
                    [alertView hide];
                }
                else
                {
                    NSLog(@"button 2 cancel");
                    [alertView hide];
                }
            }
    
            }];
    
            [changeImageAlertView show];
    
    }
    
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        _book.largeBookImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        _book.largeBookImage = [self scaleImage:_book.largeBookImage toSize:CGSizeMake(120, 168)];
        _bookImageView.image = _book.largeBookImage;
    
        _book.wasNewImageAdded = YES;
        _book.originalImageUsed = NO;
    
        NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        [self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
    
    }
    
    -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    -(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
    {
        if ([[extension lowercaseString] isEqualToString:@"png"])
        {
            [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
    
            //Create a URL to the local file
            NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]]];
            if (resourceURL)
            {
                CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
                //create a record object
                CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:@"Bookcover"];
                //set the record's fields
                bookCover[@"title"] = _book.title;
                bookCover[@"bookImage"] = asset;
    
                /* TO SAVE A RECORD */
                //get the public database
                CKContainer *appContainer = [CKContainer defaultContainer];
                CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
                [publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
                    if (error)
                    {
                        //insert error handling
                        return;
                    }
                    //insert succesfully saved record code
                    NSLog(@"png record saved after using picker!");
                }];
            }
        }
        else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"])
        {
            [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
    
            //Create a URL to the local file
            NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]]];
            if (resourceURL)
            {
                CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
                //create a record object
                CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:@"Bookcover"];
                //set the record's fields
                bookCover[@"title"] = _book.title;
                bookCover[@"bookImage"] = asset;
    
                /* TO SAVE A RECORD */
                //get the public database
                CKContainer *appContainer = [CKContainer defaultContainer];
                CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
                [publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
                    if (error)
                    {
                        //insert error handling
                        return;
                    }
                    //insert succesfully saved record code
                    NSLog(@"jpg record saved after using picker!");
                }];
            }
        }
        else
        {
            NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
        }
    }
    
    - (UIImage *) scaleImage:(UIImage*)image toSize:(CGSize)newSize 
    {
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
        [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    
    -(void)restoreOriginalPhoto
    {
        NSLog(@"restore photo called");
    
        _book.originalImageUsed = YES;
        _book.wasNewImageAdded = NO;
    
        _bookImageView.image = _book.largeBookImage;
    
        NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        [self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
    
    
    }
    

    以下是带有imageview的标题视图:

    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 26)];
        _headerView.backgroundColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:0.8];
    
    if (section == 0)
    {
        _headerView.backgroundColor = [UIColor whiteColor];
    
        _bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 120)/2, 6, 120, 168)];
        _bookImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    
        if (_book.wasNewImageAdded)
        {
            NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
            _bookImageView.image = image;
    
        }
        else
        {
            _bookImageView.image = _book.largeBookImage;
        }
    
        if(_book.originalImageUsed)
        {
            NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
            _bookImageView.image = image;
        }
    
        UITapGestureRecognizer *bookImageTouched = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bookImageTapped:)];
        bookImageTouched.numberOfTapsRequired = 1;
        [_bookImageView addGestureRecognizer:bookImageTouched];
        _bookImageView.userInteractionEnabled = YES;
    
        [_headerView addSubview:_bookImageView];
    }
    

1 个答案:

答案 0 :(得分:0)

我终于明白了!似乎我把xcode与我的属性名称混淆了。最后,代码最终变得更加简单。

在didFinishPickingMediaWithInfo中,我创建了一个UIImage,然后将其设置为bookImageView.image。后来,当我希望能够将图像更新回原始图像时,我可以调用捆绑资产_book.largeBookImage。瞧!图像能够立即更新。

最相关的代码发布在下面。

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];

    _chosenImage = [[UIImage alloc] init];
    _chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    _bookImageView.image = _chosenImage;

    _book.wasNewImageAdded = YES;
    _book.originalImageUsed = NO;

    NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    [self saveImage:_chosenImage withFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
}

-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
    if ([[extension lowercaseString] isEqualToString:@"png"])
    {
        [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];

        [self.tableView reloadData];
    }
    else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"])
    {
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];

        [self.tableView reloadData];
    }
    else
    {
        //NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
    }
}

-(void)restoreOriginalPhoto
{   
    _book.originalImageUsed = YES;
    _book.wasNewImageAdded = NO;

    _bookImageView.image = _book.largeBookImage;
    _backgroundImage.image = _book.largeBookImage; 
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{   
    if (section == 0)
    {
      _bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 168)];
        _bookImageView.contentMode = UIViewContentModeScaleAspectFit;
        _bookImageView.clipsToBounds = YES;
        _bookImageView.layer.cornerRadius = 10.0f;

        if (_book.wasNewImageAdded)
        {
            NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:@"jpg" inDirectory:documentsDirectory];
            _bookImageView.image = image;
        }
        else
        {
            _bookImageView.image = _book.largeBookImage;
        }

        if(_book.originalImageUsed)
        {
            _bookImageView.image = _book.largeBookImage;
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(_book.originalImageUsed)
    {
        _bookImageView.image = _book.largeBookImage;
    }

    [self.tableView reloadData];
    [self.tableView setContentOffset:CGPointZero animated:NO];
}