關于調用系統相機和相冊需要在info.plist文件里面添加兩個權限Privacy - Photo Library Usage Description 和 Privacy - Camera Usage Description ,都是String類型宙刘,內容任意的字符串即可苍姜;然后使用的時候需要遵守兩個協議UIImagePickerControllerDelegate和UINavigationControllerDelegate。
func tapImage(){
present(self.uploadAlertController, animated:true, completion: nil)
self.initImagePickerController()
}
func initAlertController()
{
weak var blockSelf = self
self.uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet)
let takePhoto = UIAlertAction(title:"拍照", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
blockSelf?.actionAction(action: action)
}
let photoLib = UIAlertAction(title:"從相冊選擇", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
blockSelf?.actionAction(action: action)
}
let cancel = UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel) { (action:UIAlertAction)in
blockSelf?.actionAction(action: action)
}
self.uploadAlertController?.addAction(takePhoto)
self.uploadAlertController?.addAction(photoLib)
self.uploadAlertController?.addAction(cancel)
}
func initImagePickerController()
{
pick = UIImagePickerController()
pick.delegate = self
// 設置是否可以管理已經存在的圖片或者視頻
pick.allowsEditing = true
}
func actionAction(action:UIAlertAction)
{
if action.title == "拍照" {
self.getImageFromCamera(type: .camera)
}else if action.title == "從相冊選擇" || action.title == "更換頭像" {
self.getImageFromPhotoLib(type: .photoLibrary)
}
}
//拍照
func getImageFromCamera(type:UIImagePickerControllerSourceType)
{
pick.sourceType = type
self.present(pick, animated: true, completion:nil)
}
//相冊選擇
func getImageFromPhotoLib(type:UIImagePickerControllerSourceType)
{
pick.sourceType = type
self.present(pick, animated: true, completion:nil)
}
//MARK:- UIImagePickerControllerDelegate
func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){
let type:String = (info[UIImagePickerControllerMediaType]as!String)
//當選擇的類型是圖片
if type == "public.image"
{
let img = info[UIImagePickerControllerOriginalImage]as?UIImage
self.headImage.image = img
}
}
func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
picker.dismiss(animated:true, completion:nil)
}