iOS,object-c和swift开发ios专题iOS开发

swift获取系统相册

2016-08-04  本文已影响305人  HeavenWong

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 效果图
上一篇 下一篇

猜你喜欢

热点阅读