如何在使用相机拍摄时保存照片?

时间:2017-04-29 14:24:45

标签: ios swift uiimagepickercontroller

我有一个带UIImagePickerControllerDelegate和UINavigationControllerDelegate的视图控制器来挑选照片。

但是当我选择照片然后自动在我的相册中保存相同的照片时。

我想我在我的代码中写了这个函数

UIImageWriteToSavedPhotosAlbum(photoImage!, nil, nil, nil)

所以,我检查sourcetype等于相机然后保存照片并在相册中挑选照片而不是再次保存相同的照片 但它不起作用。发生了什么事? 它还会自动保存相同的照片 我不想保存同一张照片?

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

    let uuid = NSUUID().uuidString
    let imageName:String = uuid + ".jpg"
    let documentsPath = NSHomeDirectory().appending("/Documents/\(image)/")
    let imagePath = documentsPath.appending(imageName)
    let imageUrl = URL(fileURLWithPath: imagePath)
    print("imageUrl is here:\(imageUrl)")

    photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage

    if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {

        photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage
        // this doesn't work!!!!  
        //UIImageWriteToSavedPhotosAlbum(photoImage!, nil, nil, nil)
    }

    //save image to local Documents
    let imageData:Data = UIImageJPEGRepresentation(photoImage!, 0.05)!
    do {
        try imageData.write(to: imageUrl,options: .atomic)
    } catch let error {
        print(error)
    }

    showLoading()

    hideLoading {

        //I have func upload image to server
        self.tableView.reloadData()
        self.dismiss(animated: true, completion: nil)
    }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

    self.dismiss(animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:1)

您没有检查图像选取器控制器的源类型,而是检查相机是否可用。

改变这个:

if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {

为:

if picker.sourceType == .camera {