The user can choose whether he wants to use an existing image or take a new one for use as the background.
Everything works as far as the FirstViewController is concerned. Sadly the image is no longer set as the background when the SecondViewController is displayed.
How do I enable the use of the image as background for the SecondViewController?
I used this piece of code (in the SecondViewController):
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
int bla = [prefs integerForKey:@"background_key"];
if (bla == 1) {
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"1.mac.jpg"]];
} else if (bla == 2) {
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"black.jpg"]];
} else if (bla == 3) {
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pinn.png"]];
} else if (bla == 4) {
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MyImage.png"]];
}
I tried to save the chosen image as "MyImage.png" but it looks as though it did not work. The background is black instead of the image displayed.
I used this code (from the 1stViewController) to save the chosen picture as "MyImage.png":
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)anInfo {
//UIImage *selectedImage;
NSURL *mediaUrl;
mediaUrl = (NSURL *)[anInfo valueForKey:UIImagePickerControllerMediaURL];
if (mediaUrl == nil)
{
selectedImage = (UIImage *) [anInfo valueForKey:UIImagePickerControllerEditedImage];
if (selectedImage == nil)
{
selectedImage = (UIImage *) [anInfo valueForKey:UIImagePickerControllerOriginalImage];
NSLog(@"Original image picked.");
}
else
{
NSLog(@"Edited image picked.");
}
}
[picker dismissModalViewControllerAnimated:YES];
if (selectedImage != nil)
{
self.view.backgroundColor = [UIColor colorWithPatternImage:selectedImage];
}
// Get the image from the result
UIImage* ownImage = [anInfo valueForKey:UIImagePickerControllerOriginalImage];
// Get the data for the image as a PNG
NSData* imageData = UIImagePNGRepresentation(ownImage);
// Give a name to the file
NSString* imageName = @"MyImage.png";
// Now, we have to find the documents directory so we can save it
// Note that you might want to save it elsewhere, like the cache directory,
// or something similar.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
// and then we write it out
[imageData writeToFile:fullPathToFile atomically:NO];
return;
}
There must be a mistake or logical mistake. Help would be appreciated!