Search code examples
swiftxcodeswift3uiimagepickercontrollerphphotolibrary

Swift 3 save an image taken from camera and save path on database


I can take a picture with phone save it on gallery, but I don't know how can stock the path of picture, so after I can retrieve it from gallery (I don't know yet how retrieve a picture by his path) to show it on my controller.

I have this code which works fine. I can see my image saved on gallery but I don't know how to get his url, witch I want to save on 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)
    }
}

I read that I can use PHPhotoLibrary, but it give me error that it can't cast to nsurl Here is what I tried

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;
    })
} 

Solution

  • I found a solution here but i edit it because i couldn't load the image after the application was closed, here is my solution hope it will help someone :)

    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")
        }
    
    }
    

    and to fetch the image that i just saved, i use this function

    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();
    
    }