如何将选中的照片从iPhone Photo Library保存到文档目录中?

时间:2018-05-31 07:04:31

标签: ios uiimagepickercontroller swift4.1

  

错误域= NSCocoaErrorDomain代码= 257“文件”IMG_0125.PNG“   因为你没有权限查看它而无法打开。“   的UserInfo = {NSFilePath =的/ var /移动/媒体/ DCIM / 100APPLE / IMG_0125.PNG,   NSUnderlyingError = 0x1c045d130错误域= NSPOSIXErrorDomain代码= 1   “不允许操作”}}

使用以下代码

时出现上述错误
 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

1 个答案:

答案 0 :(得分:0)

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

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{
            }
        }