The*_*mad 3 image file ios swift
使用Swift我试图JPG从URL 下载,然后将该图像保存到文件,但当我尝试将其保存到不同的目录时,它不会.它会下载到应用程序的Documents文件夹,但不会在我尝试设置另一个子文件夹的路径时.
let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0].stringByAppendingPathComponent("SubDirectory") as String
let filepath = dir.stringByAppendingPathComponent("test.jpg")
UIImagePNGRepresentation(UIImage(data: data)).writeToFile(filepath, atomically: true)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它不会将图像保存到它?为什么会这样?我需要事先创建子文件夹吗?
几点想法:
子目录文件夹是否已存在?如果没有,您必须先创建它.现在建议使用NSURL而不是路径字符串.这样产量:
let filename = "test.jpg"
let subfolder = "SubDirectory"
do {
let fileManager = NSFileManager.defaultManager()
let documentsURL = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let folderURL = documentsURL.URLByAppendingPathComponent(subfolder)
if !folderURL.checkPromisedItemIsReachableAndReturnError(nil) {
try fileManager.createDirectoryAtURL(folderURL, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = folderURL.URLByAppendingPathComponent(filename)
try imageData.writeToURL(fileURL, options: .AtomicWrite)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)我建议不要将其转换NSData为a UIImage,然后将其转换回a NSData.如果需要,您可以直接编写原始NSData对象.
通过a往返这一过程UIImage可能会导致丢失质量和/或元数据,从而可能使得到的资产变得更大,等等.通常情况下应该使用原始资产NSData.
| 归档时间: |
|
| 查看次数: |
2971 次 |
| 最近记录: |