基于swift的相册访问问题

本文介绍如何在iOS应用中实现从相册选取图片及使用相机拍照的功能,并提供了具体的Swift代码实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相册访问

访问相册首先需要在info.plist 配置一个权限

    NSPhotoLibraryUsageDescription

我的访问设置代码如下

func imagebtn(){

   let actionSheet = UIAlertController(title: "上传头像", message: nil, preferredStyle: .actionSheet)
    let cancelBtn = UIAlertAction(title: "取消", style: .cancel, handler: nil)


    let takePhotos = UIAlertAction(title: "拍照", style: .destructive, handler: {
        (action: UIAlertAction) -> Void in
        //判断是否能进行拍照,可以的话打开相机
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.sourceType = .camera
            picker.delegate = self
            picker.allowsEditing = true
            self.present(picker, animated: true, completion: nil)

        }

    })
    let selectPhotos = UIAlertAction(title: "相册选取", style: .default, handler: {
        (action:UIAlertAction)
        -> Void in
        //调用相册功能,打开相册
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.delegate = self
        picker.allowsEditing = true
        self.present(picker, animated: true, completion: nil)

    })
    actionSheet.addAction(cancelBtn)
    actionSheet.addAction(takePhotos)
    actionSheet.addAction(selectPhotos)
    self.present(actionSheet, animated: true, completion: nil)
    }


   //协议
   extension DrawerViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{


   func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

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


   let type:String = (info[UIImagePickerControllerMediaType]as!String)
   //当选择的类型是图片
   if type=="public.image"
   {
   let img = info["UIImagePickerControllerOriginalImage"]

   let imgData = UIImageJPEGRepresentation( img! as! UIImage,0.5)

   let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
   let filePath = String.init("\(cachePath)/image.jpg")
   let url=NSURL.init(string: filePath!)

   do{
   //把图片写入内存
   try imgData?.write(to: url as! URL)

    //更新视图
    updateimage()
   let vc=runViewController()
   vc.updateFocusIfNeeded()

   }catch{


   }


   picker.dismiss(animated:true, completion:nil)
   }
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值