从本地URL(iOS)获取图像

时间:2017-07-05 21:33:47

标签: ios photos

我使用PHLibrary使用requestContentEditingInput获取照片的网址

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

此网址打印: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
}

1 个答案:

答案 0 :(得分:0)

显然苹果不允许开发者访问用户照片库中的任何和所有照片,即使他们已经接受照片使用。如果您使用的图像尚未从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)
    }
}
相关问题