这是使用的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