2010-03-04 75 views
0

我正在開發一個iPhone項目,其中需要將相機圖像保存到磁盤和文件,但以下代碼失敗: (******** ****iPhone:如何在應用程序目錄中將圖像寫入磁盤

-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 

[picker dismissModalViewControllerAnimated:YES]; 
imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 
imgglobal =imageView.image; 
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent: @"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG"]; 
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0); 
NSData *data = imageData; 
if (imageData != nil) { 
    [imageData writeToFile:newFilePath atomically:YES]; 
} 
if ([[NSFileManager defaultManager] createFileAtPath:@"~/Users/abc/Library/Application Support/iPhone Simulator/User/Applications/SAVE_IMAGE_TEST1.JPG" contents:data attributes:nil]) 
{ 
    UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Image was successfully saved to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
    [successAlert show]; 
    [successAlert release]; 
} else { 
    UIAlertView  *failureAlert = [[UIAlertView alloc] initWithTitle:@"Failure" message:@"Failed to save image to the Photo Library." delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
    [failureAlert show]; 
    [failureAlert release]; 
}  
} 
+1

您是否真的應該在計算機上指定路徑而不是在iPhone環境中? – willcodejavaforfood 2010-03-04 14:58:01

回答

3

你不應該到模擬器目錄的硬編碼路徑,這將在設備或在模擬器上覆位失敗,你也不應該保存用戶數據的任何地方,但應用程序的文件夾。

而是使用:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *pathToDocuments=[paths objectAtIndex:0]; 

這將返回應用程序的Document目錄的當前路徑,而不管它在哪裏運行或發生了什麼變化。

您不應該在iPhone代碼中使用絕對路徑,因爲系統會對路徑進行加擾以提高安全性。始終使用根據需要動態檢索路徑的函數。

相關問題