基于swift的相册访问问题

    xiaoxiao2021-04-12  28

    相册访问

    访问相册首先需要在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) } }
    转载请注明原文地址: https://ju.6miu.com/read-667180.html

    最新回复(0)