0

facing with one problem,How to store images in NSUserDefaults that image contains url like this (www.example.com/1.png),how to store that images help me please. Here is my code,

listBannerArray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

imageArray = [listBannerArray valueForKey:@"mainbanner"];
NSLog(@"%@",imageArray);

NSUserDefaults *imageDefaults = [NSUserDefaults standardUserDefaults];
        [imageDefaults setObject:imageArray forKey:@"kPrefKeyForMainBanner"];
        NSLog(@"image :%@",[imageDefaults objectForKey:@"kPrefKeyForMainBanner"]);

Here listBannerArray is my total response and imageArray is my images array. Please help!

Thanks in advance.

TechBee
  • 1,897
  • 4
  • 22
  • 46
User558
  • 1,165
  • 1
  • 13
  • 37

3 Answers3

3

To save an image in NSUserDefaults:

[[NSUserDefaults standardUserDefaults]setObject:UIImagePNGRepresentation(image) forKey:key];

To retrieve an image from NSUserDefaults:

NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
UIImage* image = [UIImage imageWithData:imageData];
Tejas Ardeshna
  • 4,343
  • 2
  • 20
  • 39
Femina Brahmbhatt
  • 654
  • 1
  • 8
  • 16
1

You can read how to do such thing in this post, but again - it's not the best practice to do.

For correct approach, check this, for example.

Community
  • 1
  • 1
keyv
  • 2,430
  • 1
  • 18
  • 15
0

You can store and retrieve an image from NSUserDefaults like this:

NOTE:-

1.If you have UIImage object then you need to use UIImagePNGRepresentation to store .png image.

2.For .jpg/.jpeg UIImageJPEGRepresentation( lossy compression)if you use a compressionQuality value smaller than 1.0, you can lose some image quality.

[[NSUserDefaults standardUserDefaults]setObject:UIImagePNGRepresentation(image) forKey:@"yourKey"];

To retrieve an image from NSUserDefaults you can get it from NSData:

NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"yourKey"]; 
UIImage* image = [UIImage imageWithData:imageData];
Tejas Ardeshna
  • 4,343
  • 2
  • 20
  • 39
Mohammad Asif
  • 91
  • 1
  • 6