X0r0N X0r0N - 1 year ago 232
iOS Question

How do i get an image from the iOS photo library and display it in 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];

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?

Answer Source

you can use UIImagePickerController delegate to select the image (or url) you want to edit.

you can do this like this:

UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];

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.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//You can retrieve the actual UIImage
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
//Or you can get the image url from AssetsLibrary
    NSURL *path = [info valueForKey:UIImagePickerControllerReferenceURL];

    [picker dismissViewControllerAnimated:YES completion:nil];