Ethan Allen
Ethan Allen

Reputation: 14835

How can I save an image on my iOS device from NSData?

I have the following code to get an image from a URL and store it in NSData:

 NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pictureurl]];

How can I take this data and store it to my iOS device as an image named myimage.jpg that I can access later?

Upvotes: 1

Views: 2006

Answers (1)

wattson12
wattson12

Reputation: 11174

create the path for where you want to write the data to

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];

The write the NSData to file

[imageData writeToFile:path atomically:YES];

If you want to get the image back its:

UIImage *imageFromFile = [UIImage imageWithContentsOfFile:path];

Upvotes: 4

Related Questions