Search code examples
iosobjective-cuiwebview

How do I get an image from the iOS photo library and display it in UIWebView


I've seen a lot of examples where you use the UIImage for outputting an image. I would like the output to be set to a UIWebView because I want to put some additional HTML formatting around the image.

I want to get the photo library to return the relative path of an image stored on the iOS device, so that the I can put that in the 'src' attribute of the 'img' HTML tag.

Is this possible?


Edit 1

I had to modify my code for what I wanted but this doesn't seem to work.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //Get Image URL from Library
    NSURL *urlPath = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSString *urlString = [urlPath absoluteString];
    NSLog(urlString);

    NSURL *root = [[NSBundle mainBundle] bundleURL];
    NSString *html;
    html = @"<img src='";
    html = [html stringByAppendingString:urlString];
    html = [html stringByAppendingString:@"' />"];
    [MemeCanvas loadHTMLString:html baseURL:root];

    [picker dismissViewControllerAnimated:YES completion:^{}];
}

I am able to log the asset-library URL but it doesn't seem to be displayed the image on the UIWebView. I don't know what I need to change the baseURL to.

Any help appreciated.


Edit 2

I changed UIImagePickerControllerReferenceURL to UIImagePickerControllerMediaURL and now it crashes because it doesnt like it when i append it to a string with stringByAppendingString:urlString

It gives me the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString stringByAppendingString:]: nil argument'

Do you know what could be causing this?


Solution

  • [Updated to swift 4] You can use UIImagePickerController delegate to select the image (or url) you want to edit.

    you can do this like this:

    let pickerController = UIImagePickerController()
    pickerController.sourceType = .photoLibrary
    pickerController.delegate = self
    self.navigationController?.present(pickerController, animated: true, completion: {
    })
    

    in the delegate implementation you can use the path of the image or the image itself:

    // This method is called when an image has been chosen from the library or taken from the camera.
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {    
       //You can retrieve the actual UIImage
       let image = info[UIImagePickerControllerOriginalImage] as? UIImage
       //Or you can get the image url from AssetsLibrary
       let path = info[UIImagePickerControllerReferenceURL] as? URL
       picker.dismiss(animated: true, completion: nil)
    }