user3069029
user3069029

Reputation: 211

How to save an image when button is clicked

I'm creating an application there is a save button to save an image in another view controller. i.e., press the save button on one view controller and image should be saved on another view controller and it should not remove until i manually do with delete button in my app.

I tried with NSUserDefault but if i closed the app and reopen it the saved image is automatically remove. How to preserve that image until the user made manually.

//view controller 1 
if(count == 0) {
    [testArray addObject:imageArray[0]];
    [testArray addObject:imageArray[1]];
}

[[NSUserDefaults standardUserDefaults] setValue:testArray forKey:@"testArray"];
[[NSUserDefaults standardUserDefaults] synchronize];

//view controller 2
NSMutableArray *arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"testArray"];

Or else i want to know how to save or pass an image in one view controller to another view controller.

Upvotes: 1

Views: 526

Answers (1)

Sunny Shah
Sunny Shah

Reputation: 13020

you should save image in Document Directory

 - (IBAction)saveImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *image = imageView.image;
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO];   
}

in Another ViewController get image

  - (IBAction)getImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
    UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}

Remove image

     - (void)removeImage
    {
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

      NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
     BOOL success = [fileManager removeItemAtPath:filePath error:&error];
      if (success) {
          UIAlertView *removeSuccessFulAlert=[[UIAlertView alloc]initWithTitle:@"Congratulation:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
          [removeSuccessFulAlert show];
[imageview removeFromSuperview];
      }
      else
      {
          NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
      }
    }

Upvotes: 2

Related Questions