[英]How to save an image when button is clicked
我正在創建一個應用程序,有一個保存按鈕可以將圖像保存在另一個視圖控制器中。 即,按一個視圖控制器上的保存按鈕,圖像應保存在另一視圖控制器上,並且除非我在我的應用程序中手動執行刪除按鈕,否則圖像不應刪除。
我嘗試使用NSUserDefault,但如果我關閉了該應用程序並重新打開,則保存的圖像會自動刪除。 在用戶手動制作之前如何保存該圖像。
//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"];
否則我想知道如何在一個視圖控制器中保存或傳遞圖像到另一個視圖控制器。
您應該將圖像保存在文檔目錄中
- (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];
}
在另一個ViewController中獲取圖像
- (IBAction)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
}
移除圖片
- (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]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.