swift获取系统相册

作者: HeavenWong | 来源:发表于2016-08-04 09:12 被阅读305次

    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 效果图

    相关文章

      网友评论

        本文标题:swift获取系统相册

        本文链接:https://www.haomeiwen.com/subject/xjtcsttx.html