从本地 URL 获取图像 (iOS)

乔什·奥康纳

我使用 PHLibrary 使用 requestContentEditingInput 获取照片的 URL

asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
    let url = input?.fullSizeImageURL
}

此 URL 打印:file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.

如何检索此图像?我已经尝试了以下但它没有返回任何内容:

var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject  {
    //asset.firstObject does not exist
}
乔什·奥康纳

显然,即使开发人员接受了照片使用,苹果也不允许开发人员访问用户照片库中的任何和每张照片。如果您使用的图像不是从 imagePicker 中选取的(即选择库中的最后一张图像),则必须先将图像存储在文档目录中,然后才能使用文档目录 URL。我想这可以防止人们侵入他人的照片库

//Storing the image (in my case, when selecting last photo NOT via imagePicker)

let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)


//Retrieving the image
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
    let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image01.jpg")
    if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
        //do whatever you want with this image
        print(imageRetrieved)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章