Swift 3保存从相机拍摄的图像并保存数据库中的路径

时间:2018-01-31 19:26:46

标签: swift xcode swift3 uiimagepickercontroller phphotolibrary

我可以用手机拍照将它保存在画廊中,但我不知道如何存储图片的路径,所以我可以从图库中检索它(我不知道如何检索他的路径上的照片)在我的控制器上显示。

我有这个代码工作正常。我可以看到我的图像保存在图库中,但我不知道如何获取他的网址,女巫我想保存在coredata

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    exerciceImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    exerciceImage.isHidden = false;

    UIImageWriteToSavedPhotosAlbum(exerciceImage.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let name = image.accessibilityIdentifier;

        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}

我读到我可以使用PHPhotoLibrary,但它给我的错误是它无法转换为nsurl 这是我试过的

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    imagePicker.dismiss(animated: true, completion: nil)
    exerciceImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    exerciceImage.isHidden = false;

    PHPhotoLibrary.shared().performChanges({
        let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: info[UIImagePickerControllerOriginalImage] as! URL)
        let assetPlaceholder = assetRequest?.placeholderForCreatedAsset
    }, completionHandler: { success, error in
        // completion handling
        let url = info[UIImagePickerControllerOriginalImage] as! URL;
    })
} 

1 个答案:

答案 0 :(得分:4)

我找到了解决方案here 但我编辑它是因为我无法在应用程序关闭后加载图像,这是我的解决方案希望它能帮助某人:)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    imagePicker.dismiss(animated: true, completion: nil)
    exerciceImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    exerciceImage.isHidden = false;

    let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let imageUniqueName : Int64 = Int64(NSDate().timeIntervalSince1970 * 1000);
    let filePath = docDir.appendingPathComponent("\(imageUniqueName).png");

    do{
        if let pngImageData = UIImagePNGRepresentation((info[UIImagePickerControllerOriginalImage] as? UIImage)!){
            try pngImageData.write(to : filePath , options : .atomic)
            currentExerciceDto.imageCustom = "\(imageUniqueName).png"
        }
    }catch{
        print("couldn't write image")
    }

}

以及获取我刚刚保存的图片,我使用此功能

public static func fetchData(nameImage : String) -> UIImage{

    let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let filePath = docDir.appendingPathComponent(nameImage);

    if FileManager.default.fileExists(atPath: filePath.path){
        if let containOfFilePath = UIImage(contentsOfFile : filePath.path){
            return containOfFilePath;
        }
    }
    return UIImage();

}