简体   繁体   中英

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. ie, 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.

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]);
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM