1.遵守協(xié)議
UIImagePickerControllerDelegate,UINavigationControllerDelegate
- 方法, 拍照或者從系統(tǒng)相冊獲取
//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

效果圖