iosalassetslibraryafhttpclient

Download Image with AFHTTP and save it to ALAsset


Does anyone know how to save an image to the Asset Library? I know that saving it to the Asset, the image will be available also in the Gallery of the iPad.

I know how to get the file:

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:downloadRequest];

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

// How to make the filepath? 
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation.responseData writeToFile:filePath atomically:YES];
}

Solution

  • In order to write an image into the assets library, you can use any of the three methods below (defined in class ALAssetsLibrary):

    – writeImageToSavedPhotosAlbum:orientation:completionBlock:
    – writeImageDataToSavedPhotosAlbum:metadata:completionBlock:
    – writeImageToSavedPhotosAlbum:metadata:completionBlock:
    

    This requires that your image is either represented as a UIImage, a CGImageRef or a NSData object.

    For example, you might save your image using a NSOutputStream associated to a temporary file. Then, create and initialize a UIImage with that file and write it into the assets library using the above method.

    Alternatively, load the image as a NSData object (if it fits nicely into memory) and again use the appropriate method above, along with meta information.

    See also: ALAssetsLibrary Class Reference

    Edit:

    If you want to get more information about how to setup the metadata parameter, you may find this blog post valuable: Adding metadata to iOS images the easy way.

    And if you want to add Geolocations to your image metadata on SO: Saving Geotag info with photo on iOS4.1