這是使用的URL直接獲得一個鏈接到tmp目錄的首選方法,然後返回該目錄中的文件URL(pkm.jpg):
雨燕4.0
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("pkm")
.appendingPathExtension("jpg")
print("Filepath: \(tmpURL)")
// Then write to disk
if let url = tmpURL, let data = UIImageJPEGRepresentation(image, 0.8) {
// Use do-catch for error handling, disk can be full etc.
try? data.write(to: url)
}
雨燕3.1
let tmpURL = try! URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("pkm")
.appendingPathExtension("jpg")
print("Filepath: \(tmpURL)")
請注意,不處理可能的錯誤!
夫特2.0
let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let fileURL = tmpDirURL.URLByAppendingPathComponent("pkm").URLByAppendingPathExtension("jpg")
print("FilePath: \(fileURL.path)")
目標C
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"pkm"] URLByAppendingPathExtension:@"jpg"];
NSLog(@"fileURL: %@", [fileURL path]);
注意,一些方法仍然要求作爲字符串的路徑,然後使用[fileURL path]
返回路徑的字符串(如如上所示在NSLog中)。 當升級當前應用程序的所有文件夾:
<Application_Home>/Documents/
<Application_Home>/Library/
保證是從舊版本(不包括<Application_Home>/Library/Caches
子目錄)保存。使用Documents
文件夾查找您可能希望用戶有權訪問的文件以及Library
文件夾,查找App使用且用戶看不到的文件。
另一個更長的路可能獲得一個網址到tmp目錄,首先,把文件目錄和剝離的最後一個路徑組件,然後添加tmp文件夾:
NSURL *documentDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *tmpDir = [[documentDir URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"tmp" isDirectory:YES];
NSLog(@"tmpDir: %@", [tmpDir path]);
然後我們能夠針對文件存在,即pkm.jpg如下所示:
NSString *fileName = @"pkm";
NSURL *fileURL = [tmpDir URLByAppendingPathComponent:fileName isDirectory:NO];
fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];
可以使用字符串完成相同的操作,但在上面的第一個URL方法是現在推薦的方法(除非您正在寫入較舊的系統:iPhone OS 2或3):
NSString *tmpDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
tmpDir = [[tmpDir stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"tmp"];
NSString *filePath = [[tmpDir stringByAppendingPathComponent:@"pkm"] stringByAppendingPathExtension:@"jpg"];
這篇文章解釋了iOS應用程序的所有目錄,保存,刪除http://kmithi.blogspot.in/2012/08/ios-application-directory-structure.html – mithilesh
'UIImageJPEGRepresentation()'已經返回'NSData * ' - 爲什麼在使用它之前將它傳遞給'dataWithData:'?我想知道你是否知道我不知道的東西... – ArtOfWarfare