在 Swift 中创建相册,可以通过使用 UIImagePickerControllerPHPhotoLibrary 类来实现。下面是一个简单的示例代码,展示了如何创建相册并保存照片:

import UIKit
import Photos

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

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

    @IBAction func openCameraButtonTapped(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            present(imagePicker, animated: true, completion: nil)
        }
    }

    // UIImagePickerControllerDelegate 方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
            saveImageToAlbum(image: image)
        }
        picker.dismiss(animated: true, completion: nil)
    }

    // 保存照片到相册
    func saveImageToAlbum(image: UIImage) {
        PHPhotoLibrary.requestAuthorization { (status) in
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAsset(from: image)
                }) { (success, error) in
                    if success {
                        print("照片保存成功")
                    } else {
                        print("照片保存失败:\(error?.localizedDescription ?? "")")
                    }
                }
            }
        }
    }
}

这个示例中,我们首先检查相机是否可用,然后创建一个 UIImagePickerController 对象,并设置其代理为当前视图控制器。当用户拍摄照片后,我们将调用 imagePickerController(_:didFinishPickingMediaWithInfo:) 方法,将照片保存到相册中。

为了保存照片到相册,我们需要请求用户授权访问相册,可以通过调用 PHPhotoLibrary.requestAuthorization 方法来请求授权。然后,我们使用 PHPhotoLibrary.shared().performChanges 方法在相册中创建一个 PHAssetChangeRequest 对象,并将照片添加到相册中。

请注意,为了能够访问相册,您需要在项目的 Info.plist 文件中添加一个相册访问权限的描述。可以在 Privacy - Photo Library Usage Description 键中添加一个自定义描述,向用户解释为什么需要访问相册

swift 创建相册

原文地址: http://www.cveoy.top/t/topic/hMoH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录