如何将从 iPhone 图片库中选择的照片保存到文档目录中?

How do I save the selected photos from iPhone Photo Library into the document directory?

Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0125.PNG” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0125.PNG, NSUnderlyingError=0x1c045d130 Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

我在使用以下代码时出现上述错误

do{
    try filemanager.copyItem(at: sourceURL, to: dirConPath1)
}catch let error as NSError{
    print(error.debugDescription)
}

我还补充了:

    <key>NSPhotoLibraryUsageDescription</key>
    <string>want access of photos</string>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>photos save description.</string>

进入info.plist

我正在使用 Swift 4.1 和 Xcode 9.3.1。

如果您想将图像保存在本地目录中,请将此方法放入您的文件中,然后使用您的图像和图像名称调用...

func saveImageToDocumentLocal(name:String,image:UIImage)  {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                let random = arc4random()
                let fileURL = documentsDirectory.appendingPathComponent("\(name)\(random)")
                if let data = UIImageJPEGRepresentation(image, 0.5),
                        !FileManager.default.fileExists(atPath: fileURL.path) {
                        do {
                            try data.write(to: fileURL)
                            print("file saved")
                            print(fileURL.path)

                        } catch {
                            print("error saving file:", error)
                        }
                }else{
            }
        }