swift获取系统相册

1.遵守协议

UIImagePickerControllerDelegate,UINavigationControllerDelegate
  • 方法, 拍照或者从系统相册获取
//MARK:拍照或相册选择
    func choicePhotoWithType(type: UIImagePickerControllerSourceType) {
        if UIImagePickerController.isSourceTypeAvailable(type) {
            let picker = UIImagePickerController.init()
            picker.delegate = self//代理
            picker.sourceType = type//来源
            picker.allowsEditing = true
            self.presentViewController(picker, animated: true, completion: nil)
        }else {
            let str: String?
            if type == UIImagePickerControllerSourceType.Camera {
                str = "摄像头不可用"
            }else
            {
                str = "相册不可用"
            }
            let alertController: UIAlertController = UIAlertController.init(title: "温馨提示", message: str, preferredStyle: UIAlertControllerStyle.Alert)
            let action: UIAlertAction = UIAlertAction.init(title: "知道了", style: UIAlertActionStyle.Default, handler: { (action) in
                alertController.dismissViewControllerAnimated(true, completion: nil)
            })
            alertController.addAction(action)
            presentViewController(alertController, animated: true, completion: nil)
        }
    }

  • 保存照片
//保存图片到本地
    func savePhotoToLibrary(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PersionViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject) {
        if didFinishSavingWithError != nil {
            print("\(didFinishSavingWithError)")
        }else
        {
            print("保存图片成功")
        }
    }

  • 代理方法
// 选择完毕后获得照片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image:UIImage = info["UIImagePickerControllerEditedImage"] as! UIImage
        // 拍照
        if picker.sourceType == UIImagePickerControllerSourceType.Camera {
            savePhotoToLibrary(info["UIImagePickerControllerOriginalImage"] as! UIImage)
        }
        headView.iconImageView.image = image
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }

效果图 2
效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容