save image in nsuserdeafult from image picker and get other view controller - ios

I save image using NSUaerDefaults from image picker using this code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imagedata=[NSData dataWithData:UIImagePNGRepresentation(image)];
NSUserDefaults *default_bg=[NSUserDefaults standardUserDefaults];
[default_bg setObject:imagedata forKey:#"image"];
[default_bg synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
}
and getting in other view controller using this code:
NSUserDefaults *defaults_bgvw = [NSUserDefaults standardUserDefaults];
[defaults_bgvw synchronize];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[defaults_bgvw objectForKey:#"image"]]];
//bgImageView.contentMode=UIViewContentModeScaleAspectFit;
bgImageView.frame = self.view.bounds;
[self.view addSubview:bgImageView];
[self.view sendSubviewToBack:bgImageView];
When I run this code getting error like
"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData hasPrefix:]: unrecognized selector sent to instance 0x147c8590'"

Never user NSUserDefaults to store images or other large amounts of data. You should simply store the file on the file system.
That aside, your code to create an image from the stored data is flawed. You want this instead:
NSData *imageData = [defaults_bgvw objectForKey:#"image"];
UIImage *bgImage = [UIImage imageWithData:imageData];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:bgImage];
Note how the code is split up. This is easier to read and much easier to debug.
But again, do not store images in NSUserDefaults.
Unrelated but the following line:
NSData *imagedata=[NSData dataWithData:UIImagePNGRepresentation(image)];
can simply be:
NSDate *imagedata = UIImagePNGRepresentation(image);
No need to create the extra NSDate instance.
And don't needlessly call synchronize. The following:
NSUserDefaults *defaults_bgvw = [NSUserDefaults standardUserDefaults];
[defaults_bgvw synchronize];
should simply be:
NSUserDefaults *defaults_bgvw = [NSUserDefaults standardUserDefaults];
A call to synchronize is rarely needed at all and it definitely is never needed just to read values.

You can save & load custom object into NSUserDefault using following methods. You need to use NSKeyedArchiver class for the same.
Alternate 1 :
- (void)saveCustomObject:(UIImage *)object key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:key];
[defaults synchronize];
}
- (UIImage *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
UIImage *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
Alternate 2 :
Save image to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:#"myImage"];
Retrieve Image from NSUserDefaults
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:#"myImage"];
UIImage* image = [UIImage imageWithData:imageData];

Related

Empty NSCFConstantString in stored UserDefaults

I have a problem with a stored userDefaults array.
I have a simple object (in the image I have cut off some variables) with two strings mutableArray.
When I save this object in the userDefaults I have the same object in the top (of the image), the problem occurs when I retrieve the object; I have the object in the bottom (added by me in a mutableArray, same object before add it).
the problem is that I make comparisons between objects and it returns false because there is an empty NSCFConstantString in the second array.
These are the two methods to store and retrieve the object in the userDefaults:
- (void)saveCustomObject:(NSMutableArray *)object key:(NSString *)key
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:object] forKey:key];
[defaults synchronize];
}
- (NSArray *)loadCustomObjectWithKey:(NSString *)key
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:key];
NSMutableArray *objectArray = nil;
if (dataRepresentingSavedArray != nil)
{
NSArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (savedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:savedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
return objectArray;
}
I would prefer not to have to write logic to handle this empty string.
Where is it coming from?

Star rating view with user default in objective c

I have a star rating view which uses custom class RateView.m and .h files to show the star rating image and a label to show how much rating is given as given below:
Now when the rating is clicked, the selected image is shown and when unselected another image is shown.
This Rateview calls a delegate when that rateview is clicked
- (void)rateView:(RateView *)rateView ratingDidChange:(float)rating {
self.statusLabel.text = [NSString stringWithFormat:#"Rating: %0.1f/5.0", rating];
NSString *valueToSave = self.statusLabel.text;
// self.rateView.fullSelectedImage = [UIImage imageNamed:#"yellow-rating.png"];
// UIImage *contactImage = self.rateView.fullSelectedImage;
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"ratingSelected"];
// [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(contactImage) forKey:#"image"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
In viewwillappear method it is as shown:
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"ratingSelected"];
self.statusLabel.text = savedValue;
NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:#"image"];
// NSLog(#"imagedata is %#",imageData);
UIImage *contactImage = [UIImage imageWithData:imageData];
NSLog(#"contactImage is %#",contactImage);
// self.rateView.fullSelectedImage = contactImage;
self.rateView.fullSelectedImage = [UIImage imageNamed:#"yellow-rating.png"];
}
Now the issue is i can see the label with correct rating,but the image is not saved using userdefault.
How to also save the image using userdefault in my case.
You can save image to disc (for example Document directory) and store only image's path in NSUserDefaults
See this answer

Attempt to set a non-property-list object [duplicate]

This question already has answers here:
Attempt to set a non-property-list object as an NSUserDefaults
(12 answers)
Closed 8 years ago.
NSMutableArray *mutableArray = [NSMutableArray array];
Prostate *prostate = [Prostate new];
prostate.prostateCheckTimeString = self.prostateCheckTime.text;
prostate.prostateCubeString =self.prostateCube.text;
prostate.prostateAntigemString =self.prostateAntigem.text;
prostate.peeSpeedMaximumString =self.peeSpeedMaximum.text;
prostate.peeRemenderString =self.peeRemender.text;
[mutableArray addObject:prostate];
NSArray *tempArray = [[NSArray alloc]initWithArray:self.mutableArray];
[Global saveArrayToUserDefault:prostateArray saveValue:tempArray];
NSArray *array = [Global getArrayFromUserDefault:prostateArray];
//Below is my global object
**+(void)saveArrayToUserDefault:(NSString *)userDefaultKey saveValue:(NSArray *)value**
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:value forKey:prostateArray];
[userDefaults synchronize];
}
**+(NSArray *)getArrayFromUserDefault:(NSString *)userDefaultKey**
{
NSArray *temp;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
temp = [userDefaults objectForKey:userDefaultKey];
return temp;
}
-----------------------------------Description ---------------------------------------
I had Been Search for a while , I know NSUserDefault can only store NSArray , I tried to convert NSMutableArray to NSArray , but still got error
-----------------------------------Error ---------------------------------------------
Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType') Attempt to set a non-property-list object (
""
Implement the <NSCoding> protocol in your entity class which you wanna save
-(void)writeArrayWithCustomObjToUserDefaults:(NSString *)keyName withArray:(NSMutableArray *)myArray {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[defaults setObject:data forKey:keyName];
[defaults synchronize]; }
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[defaults synchronize];
return myArray; }
Prostate is your custom object and NSUserDefaults does not allow you to save it.
So you have to Archive it before saving to NSUserDefaults and Unarchive it when reading back from NSUserDefaults.
So your methods to save and read user defaults data should look like:
-(void)writeArrayWithCustomObjToUserDefaults:(NSString *)keyName withArray:(NSMutableArray *)myArray {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[defaults setObject:data forKey:keyName];
[defaults synchronize];
}
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
return myArray;
}

how to hide Outlet in Xcode and save it from never appearing again?

I want to hide a outlet that is also a button after the action is made, then I need it to be saved so it doesn't appear again.
Ive used in the cation
- (IBAction)giveheart:(id)sender {
[_heartM setHidden:YES];
nLife = [lblLife.text intValue]+1;
[savedStock setObject:[NSNumber numberWithFloat:nLife] forKey:#"life"];
[savedStock writeToFile: path atomically:YES];
}
Now I need to save it to not appear again even when the app is turned off and on again.
How is that done, and what should I do?
Save the state in the NSUserDefaults when button pressed.
- (IBAction)giveheart:(id)sender {
//Save the state in NSUserDefaults here
[[NSUserDefaults standardUserDefaults]setObject:#"Yes" forKey:#"hide"];
[[NSUserDefaults standardUserDefaults]synchronize];
[_heartM setHidden:YES];
nLife = [lblLife.text intValue]+1;
[savedStock setObject:[NSNumber numberWithFloat:nLife] forKey:#"life"];
[savedStock writeToFile: path atomically:YES];
}
in ViewDidLoad method of the viewcontroller
NSString *status = [[NSUserDefaults standardUserDefaults]objectForKey:#"hide"];
if(status != nil && [status isEqualToString:#"Yes"] )
[_heartM setHidden:YES];
You can save the state of the button to NSUserDefaults as follows.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSNumber numberWithBool:_heartM.isHidden] forKey:#"buttonState"];
[userDefaults synchronize];
When you view is loaded, you can get the status of button from the defaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *boolNum = [userDefaults objectForKey:#"buttonState"];
if(boolNum) {
_heartM.hidden = [boolNum boolValue];
}

How do I make this save button save entered text onto a new page?

- (IBAction)Save:(id)sender {
NSString *saveString = taskName.text;
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:saveString forKey:#"savedString"];
[defults synchronize];
//use data that has been given
}
- (IBAction)theTask:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:#"savedString"];
[taskName setText:loadstring];
[super viewDidLoad];
}
Im trying to attach the new label i made on storyboard to attach to theTask method. So when the user types in a task and pushes save the task is placed in a list of other tasks

Resources