How do I save an image to the camera roll?

Discussion in 'iOS Programming' started by ViviUO, Nov 11, 2010.

  1. ViviUO macrumors 6502

    Joined:
    Jul 4, 2009
    #1
    First, I am a little new to iOS programming.

    After searching through the SDK documentation, I was unable to find a solution to saving an image to the camera roll.

    For instance, lets say I wanted to make an app that displayed a "picture of the day" from a website inside of a UIWebView. I am going to use an IBOutlet connected to a button, which will then save the image to the phone.

    This is probably very easy to implement, but I am absolutely stumped. Thanks in advance.
     
  2. ViviUO thread starter macrumors 6502

    Joined:
    Jul 4, 2009
    #2
    Okay, I think I found it:

    Code:
    void UIImageWriteToSavedPhotosAlbum (
       UIImage *image,
       id completionTarget,
       SEL completionSelector,
       void *contextInfo
    );
    So my next question is, does it HAVE to be a UIImage, or can I substitute it for an NSURL?
     
  3. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #3
    It has to be an image: it is up to you to download the contents of the URL and turn them into an image. If the URL is pointing at a jpg/png this is very easy.
     
  4. ViviUO thread starter macrumors 6502

    Joined:
    Jul 4, 2009
    #4
    What would be the easiest way to go about implementing this?
     
  5. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    I'd start with the URL Loading System Guide concentrate specifically on NSURLConnection and asynchronous loading. Once you have the data you can easily create a UIImage using the obvious method (look at the UIImage documentation for a convenience constructor that takes a NSData parameter).
     
  6. ViviUO thread starter macrumors 6502

    Joined:
    Jul 4, 2009
    #6
    Great, I will give it a look. So far I have come up with this:

    Code:
    NSURL * imageURL = [NSURL URLWithString:@"http:image.jpg"];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage * image = [UIImage imageWithData:imageData];
    This looks like it would work without any problems, i'll report back if I run into any issues.
     
  7. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #7
    It will work (in theory: I've not checked the code in detail) but will block the thread whilst it downloads the data. Which is why I suggested looking at the async methods to download data. Try what you have (especially on slower network connections like Edge). It might be OK for you, if not you know you need to go async to make it better.
     

Share This Page