سؤال

I'm working on an app that gives the user the option to take a photo for their profile picture, but can't seem to figure out how to:

  1. Get the photo to save to the users library
  2. Get that photo to replace a default photo when they press "use" (that is there when the user first loads the app)

Any suggestions? This code might be completely off but here is what I was starting to use:

- (void)takePhoto {
     UIImagePickerController *takePhotoPicker = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        takePhotoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        takePhotoPicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    } else {
        takePhotoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }

    [self presentViewController:takePhotoPicker animated:YES completion:nil];

}
هل كانت مفيدة؟

المحلول

What you need to do is register your viewController as a UIImagePickerControllerDelegate, and then do:

takePhotoPicker.delegate = self;

Then, you need to add the method:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {}

which you can use to get the image.

To get the image from the camera or photo album you need to get the value from the correct key from the info dictionary.

For example, to get the Edited image (resized by user):

UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];

And to get the original image:

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];

The original image is the full screen image that the user took with the camera.

You can then use this image to set an image view or upload to the server, etc.

Also, you shouldn't set the source type based on whether or not the camera is available, but you should let the user select (in case they want to choose from the photo album even if they have a camera).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top