不能保存tmp目录内的文件

我有这个function来保存tmp文件夹内的图像

private func saveImageToTempFolder(image: UIImage, withName name: String) { if let data = UIImageJPEGRepresentation(image, 1) { let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true) let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").absoluteString print("target: \(targetURL)") data.writeToFile(targetURL, atomically: true) } } 

但是,当我打开我的应用程序的临时文件夹,它是空的。 我在做什么错误将图像保存在临时文件夹?

absoluteString不是获取NSURL的文件path的正确方法,而是使用path

 let targetPath = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").path! data.writeToFile(targetPath, atomically: true) 

或者更好的是,只使用url:

 let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg") data.writeToURL(targetURL, atomically: true) 

更好的是,使用writeToURL(url: options) throws并检查成功或失败:

 do { try data.writeToURL(targetURL, options: []) } catch let error as NSError { print("Could not write file", error.localizedDescription) }