swift3.0调用相机和相册 简单实用

前端之家收集整理的这篇文章主要介绍了swift3.0调用相机和相册 简单实用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、首先,swift3.0中调用相机和相册会导致崩溃,需要在info.plist文件中加入两个键值对,如下:

Privacy - Photo Library Usage Description 和Privacy - Camera Usage Description ,都是String类型,内容任意的字符串即可。

2、废话少说,上代码

class MyController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var uploadAlertController:UIAlertController!

var imagePickerController:UIImagePickerController!

@IBOutletweakvar headImg:UIImageView!


overridefunc viewDidLoad() {

super.viewDidLoad()

self.initAlertController()

self.initImagePickerController()

}

func initAlertController()

{

weakvar blockSelf =self

self.uploadAlertController =UIAlertController(title:nil,message: nil,preferredStyle:UIAlertControllerStyle.actionSheet)

self.uploadAlertController.view.tintColor = DeepMainColor

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()

{

self.imagePickerController =UIImagePickerController()

self.imagePickerController.delegate = self

// 设置是否可以管理已经存在的图片或者视频

self.imagePickerController.allowsEditing = true

}

func actionAction(action:UIAlertAction)

{

if action.title =="拍照" {

self.getImageFromPhotoLib(type: .camera)

}elseif action.title =="从相册选择"|| action.title =="更换头像" {

self.getImageFromPhotoLib(type: .photoLibrary)

}elseif action.title =="删除照片" {

self.headImg.image =UIImage(named:"head")

}

}

func getImageFromPhotoLib(type:UIImagePickerControllerSourceType)

{

self.imagePickerController.sourceType = type

//判断是否支持相册

ifUIImagePickerController.isSourceTypeAvailable(.photoLibrary) {

self.present(self.imagePickerController,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.headImg.image =cropToBounds(image: img!)

let imgData =UIImageJPEGRepresentation(self.headImg.image!,0.5)

picker.dismiss(animated:true,completion:nil)

}

}

func imagePickerControllerDidCancel(_ picker:UIImagePickerController){

picker.dismiss(animated:true,completion:nil)

}

@IBActionfunc headImgTapGesture(_ sender:AnyObject) {

present(self.uploadAlertController,animated:true,completion: nil)

}

}

猜你在找的Swift相关文章