簡體   English   中英

為什么我不能將文件保存到我的iOS應用程序/ Documents目錄中?

[英]Why can't I save files to my iOS apps /Documents directory?

我正在編寫一個可以訪問iOS根系統的應用程序,該用戶應該能夠將文件保存到他的文檔目錄中。 我正在使用此代碼將文件保存到文檔目錄。

對於文字:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [self.filePath lastPathComponent]]
                                           atomically:YES
                                             encoding:NSUTF8StringEncoding error:nil];

對於其他文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory,[self.filePath lastPathComponent]]
                                           atomically:YES];

我的問題是我可以保存.txt文件,但不能保存其他文件,例如,如果使用保存文本方法保存.plist文件,則聯系人將被文件的目錄路徑替換。 當我保存圖片或任何其他文件時,它是不可讀的。 有沒有保存文件而不破壞文件的好方法?

您正在調用[self.filePath writeToFile:] ,從而將filePath變量的內容寫入文件。

您應該執行以下操作:

[contents writeToFile:...]

這里有一個保存圖像的例子:

假設您將圖像的內容放入NSData對象中:

NSData *pngData = UIImagePNGRepresentation(image);

然后將其寫入文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

請查看以下問題以獲取更詳細的解釋:

在iOS上寫入文件

從IOS上的UIView將圖像保存到應用程序文檔文件夾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM