我是 Swift 初学者,刚刚在我的应用程序中完成了我的照片相机功能。我现在遇到的问题是,当我从相机拍摄照片时,它没有保存到我 iPhone 上的照片库中。一切正常我可以拍照,但是当我检查照片时,它们似乎没有保存。 我已经检查过类似的问题,但没有找到合适的答案,我看到他们是添加按钮以直接访问照片库的人,但我不需要这样的按钮。我需要的唯一功能是拍照,当用户单击选择照片以将其保存在照片中时。
到目前为止我用过这个:
class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let imagePicker: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes))
upSwipe.direction = .up
view.addGestureRecognizer(upSwipe)
}
和函数:
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .up){
if ( UIImagePickerController.isSourceTypeAvailable(.camera)){
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
present(imagePicker,animated: true, completion: {})
}
}
最佳答案
在任何事情之前,您需要将“隐私 - 照片库添加使用说明”添加到您的 info.plist 中,否则您的应用将崩溃
使用这个:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
UIImageWriteToSavedPhotosAlbum(pickedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
dismiss(animated: true, completion: nil)
}
}
然后,添加如下函数(和saltTigerK写的函数一样)
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 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)
}
}
来源:https://www.hackingwithswift.com/read/13/5/saving-to-the-ios-photo-library
关于swift - 如何在照片库 Swift 中保存图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980863/