本文介绍了拍摄照片并保存到 Swift 中的照片库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拍照"按钮,按下它会打开相机,你拍照,当你选择使用照片"时,我想把它保存到照片库中.

除了保存到图书馆之外,我什么都能做.这是我必须打开相机的代码:

解决方案

使用以下代码获取从照片库中获取的图像并保存在照片库中.

代码支持 Swift 3.1 &4.0 版本:

首先,我们必须在项目的.plist文件中设置权限:-

1) 相机

<string>此应用将使用相机.</string>

2) 照片库

<string>您可以选择要附加到报告中的照片.</string>

3) 保存到照片库

<string>请允许访问以将照片保存在您的照片库中</string>

我们需要以源代码类型打开.pilst文件,然后在里面添加权限 -

在那之后

导入 UIKit类 ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {@IBOutlet 弱变量 imageTake:UIImageView!var imagePicker: UIImagePickerController!覆盖 func viewDidLoad() {super.viewDidLoad()}//MARK: - 拍摄图像@IBAction func takePhoto(_ sender: UIButton) {imagePicker = UIImagePickerController()imagePicker.delegate = selfimagePicker.sourceType = .camera存在(imagePicker,动画:true,完成:nil)}//MARK: - 在此处保存图像@IBAction func save(_ sender: AnyObject) {UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)}//MARK: - 将图像添加到库func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {如果让错误 = 错误 {//我们返回了一个错误!let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)ac.addAction(UIAlertAction(title: "OK", style: .default))存在(交流,动画:真实)} 别的 {let ac = UIAlertController(title: "Saved!", message: "您修改后的图片已保存到您的照片中.", preferredStyle: .alert)ac.addAction(UIAlertAction(title: "OK", style: .default))存在(交流,动画:真实)}}//MARK: - 在此处完成图像捕获func imagePickerController(_picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {imagePicker.dismiss(动画:true,完成:nil)imageTake.image = info[UIImagePickerControllerOriginalImage] as?用户界面图像}}

Swift 4.2 代码更新 -

 class ViewController: UIViewController, UINavigationControllerDelegate {@IBOutlet 弱变量 imageTake:UIImageView!var imagePicker: UIImagePickerController!枚举 ImageSource {案例照片库案例相机}覆盖 func viewDidLoad() {super.viewDidLoad()}//MARK: - 拍摄图像@IBAction func takePhoto(_ sender: UIButton) {守卫 UIImagePickerController.isSourceTypeAvailable(.camera) else {selectImageFrom(.photoLibrary)返回}selectImageFrom(.camera)}func selectImageFrom(_ source: ImageSource){imagePicker = UIImagePickerController()imagePicker.delegate = self切换源{案例.camera:imagePicker.sourceType = .camera案例.photoLibrary:imagePicker.sourceType = .photoLibrary}存在(imagePicker,动画:true,完成:nil)}//MARK: - 在此处保存图像@IBAction func save(_ sender: AnyObject) {守卫让 selectedImage = imageTake.image else {print("找不到图片!")返回}UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)}//MARK: - 将图像添加到库@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {如果让错误 = 错误 {//我们返回了一个错误!showAlertWith(title: "Save error", message: error.localizedDescription)} 别的 {showAlertWith(title: "Saved!", message: "您的图片已保存到您的照片中.")}}func showAlertWith(title: String, message: String){让 ac = UIAlertController(title: title, message: message, preferredStyle: .alert)ac.addAction(UIAlertAction(title: "OK", style: .default))存在(交流,动画:真实)}}扩展视图控制器:UIImagePickerControllerDelegate{func imagePickerController(_picker: UIImagePickerController, didFinishPickingMediaWithInfo 信息: [UIImagePickerController.InfoKey: Any]){imagePicker.dismiss(动画:true,完成:nil)守卫让 selectedImage = info[.originalImage] 作为?UIImage 其他 {print("找不到图片!")返回}imageTake.image = selectedImage}}

I have a button "take a photo" and when pressed, it opens the camera, you take a photo and when you select "Use Photo", I want it saved to the photo library.

I am able to do all but save to the library. This is the code I have to open the camera:

解决方案

Use below code for an image taken from Photo Gallery and save inside photo library.

First, we have to do the setup for Permissions inside Project's .plist file:-

1) Camera

<key>NSCameraUsageDescription</key>
<string>This app will use camera.</string>

2) Photo Library

<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>

3) Save to Photo Library

<key>NSPhotoLibraryAddUsageDescription</key>
<string>Please allow access to save photo in your photo library</string>


We need to open .pilst file as a Source code type then add permissions inside -


After That


import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

    @IBOutlet weak var imageTake: UIImageView!

  var imagePicker: UIImagePickerController!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //MARK: - Take image
    @IBAction func takePhoto(_ sender: UIButton) {
        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }

    //MARK: - Saving Image here
    @IBAction func save(_ sender: AnyObject) {
        UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }

    //MARK: - Add image to Library
    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)
        }
    }

    //MARK: - Done image capture here
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
         imagePicker.dismiss(animated: true, completion: nil)
        imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    }

}


 class ViewController: UIViewController, UINavigationControllerDelegate  {

    @IBOutlet weak var imageTake: UIImageView!
    var imagePicker: UIImagePickerController!

    enum ImageSource {
        case photoLibrary
        case camera
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //MARK: - Take image
    @IBAction func takePhoto(_ sender: UIButton) {
        guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
            selectImageFrom(.photoLibrary)
            return
        }
        selectImageFrom(.camera)
    }

    func selectImageFrom(_ source: ImageSource){
        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        switch source {
        case .camera:
            imagePicker.sourceType = .camera
        case .photoLibrary:
            imagePicker.sourceType = .photoLibrary
        }
        present(imagePicker, animated: true, completion: nil)
    }

    //MARK: - Saving Image here
    @IBAction func save(_ sender: AnyObject) {
        guard let selectedImage = imageTake.image else {
            print("Image not found!")
            return
        }
        UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }

    //MARK: - Add image to Library
    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            // we got back an error!
            showAlertWith(title: "Save error", message: error.localizedDescription)
        } else {
            showAlertWith(title: "Saved!", message: "Your image has been saved to your photos.")
        }
    }

    func showAlertWith(title: String, message: String){
        let ac = UIAlertController(title: title, message: message, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
 }

 extension ViewController: UIImagePickerControllerDelegate{

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
        imagePicker.dismiss(animated: true, completion: nil)
        guard let selectedImage = info[.originalImage] as? UIImage else {
            print("Image not found!")
            return
        }
        imageTake.image = selectedImage
    }
}

这篇关于拍摄照片并保存到 Swift 中的照片库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:07