How to upload image that was taken from UIImagePickerController

user1590031 picture user1590031 · Aug 27, 2012 · Viewed 10.8k times · Source

After user choose image from the iPhone library with UIImagePickerController, I want to upload it to my server using ASIHTTPRequest library.

I know that with ASIHTTPRequest I can upload a file with the file's URl, but how do I get the image URL?

I know I can get the image UIImagePickerControllerReferenceURL, that look like this:

"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"

is this the URL I need to use?

Answer

Shamsudheen TK picture Shamsudheen TK · Aug 27, 2012

There are two ways

1:

You can upload the image using the imagePickerController delegate

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

    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    //Upload your image
}

2:

You can save the picked image url and upload later using this

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

    NSString *imageUrl = [NSString stringWithFormat:@"%@",[info valueForKey:UIImagePickerControllerReferenceURL]];
    //Save the imageUrl
}

-(void)UploadTheImage:(NSString *)imageUrl{

 NSURL *url = [[NSURL alloc] initWithString:imageUrl];
 typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
 typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);    

 ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){

  ALAssetRepresentation *rep = [myasset defaultRepresentation];
  CGImageRef iref = [rep fullResolutionImage];
  UIImage *myImage = nil;   

  if (ref) {
      myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];

        //upload the image   
     }      
  };      

  ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror){

  };          


  ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
 [assetslibrary assetForURL:url resultBlock:result block failureBlock:failureblock];    

}

Notes: Please make sure the scope of ALAssetsLibrary object while using ARC.Better to use the ALAssetsLibrary object as a singleton.