2012-10-07 65 views
2

嘗試使用照片選擇器選擇圖像並將該圖像內部保存在應用程序文件夾中。將圖像持久保存在應用程序內 - iOS

- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info { 

NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType]; 
UIImage *originalImage, *editedImage, *imageToUse; 

// Handle a still image picked from a photo album 
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) 
    == kCFCompareEqualTo) { 

    editedImage = (UIImage *) [info objectForKey: 
           UIImagePickerControllerEditedImage]; 
    originalImage = (UIImage *) [info objectForKey: 
           UIImagePickerControllerOriginalImage]; 

    if (editedImage) { 
     imageToUse = editedImage; 
    } else { 
     imageToUse = originalImage; 
    } 
    // Do something with imageToUse 

    //save it 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]]; 
    NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"]; 

    NSData *webData = UIImagePNGRepresentation(editedImage); 
    NSError* error = nil; 
    bool success = [webData writeToFile:imagePath options:NULL error:&error]; 
    if (success) { 
     // successfull save 
     imageCount++; 
     [[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:@"imageCount"]; 
     NSLog(@"@Success save to: %@", imagePath); 
    } 
    else if (error) { 
     NSLog(@"Error:%@", error.localizedDescription); 
    } 
} 
... 
} 

我無法弄清楚什麼是writeToFile:::回報false但沒有值在error返回,所以我不能弄清楚怎麼回事錯了。任何幫助將不勝感激

回答

1

你錯過了一個「/」。行:

NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]]; 

應該是:

NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", myUniqueID]]; 

而且這行:

NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"]; 

應該是:

NSString *imagePath = [imageName stringByAppendingPathExtension:@"png"]; 

更新:

而且,不應該:

NSData *webData = UIImagePNGRepresentation(editedImage); 

是以下?

NSData *webData = UIImagePNGRepresentation(imageToUse); 
+0

感謝您的回覆。做了改變..但仍然沒有。最困惑的。 –

+0

我不知道爲什麼......但改變 NSData * webData = UIImagePNGRepresentation(editedImage); 至 NSData * webData = [NSData dataWithData:UIImagePNGRepresentation(editedImage)]; 似乎已經工作 –

+0

我不知道它爲什麼它沒有工作的第一次,但我敢打賭,如果你改變這個'NSData'行,它仍然會工作... – Rob

相關問題