iOS10.0出现了挺多坑的,访问系统的相机、麦克风、相册等都得进行设置。
今天写项目时,需要调用相机以及相册,添加一个Button,action里面添加如下代码:
let ac = UIAlertController(title: "打开相册", message: "", preferredStyle: .actionSheet)
ac.addAction(UIAlertAction(title: "是的", style: UIAlertActionStyle.default, handler: { (alert) in
let ic = UIImagePickerController()
ic.sourceType = UIImagePickerControllerSourceType.photoLibrary
ic.delegate = self
self.present(ic, animated: true, completion: nil)
}))
ac.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
self.present(ac, animated: true, completion: nil)
1.png
点击更改照片Button,触发方法,出现一个ActionSheet。
WechatIMG2.jpeg点击是的,会实例化一个UIImagePickerController,设置sourceType为photoLibrary,可以打开系统相册,选择一张照片,就会调用到UIImagePickerControllerDelegate的方法:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage]
headImage.image = image as! UIImage?
print(info)
self.dismiss(animated: true, completion: nil)
}
选择照片后,奔溃了,查看控制台的信息
解决方法:
在项目中找到info.plist文件,打开,添加键值
<key>NSPhotoLibraryUsageDescription</key>
<value>此 App 需要您的同意才能读取相册</value>
再次运行就可以访问了
3.png 4.png附上其他资源参数
<key>MediaLibraryUsageDescription</key>
<value>此 App 需要您的同意才能读取相册</value>
<key>NSCameraUsageDescription</key>
<value>访问相机</value>
<key>NSMicrophoneUsageDescription</key>
<value>访问麦克风</value>
<key>NSContactsUsageDescription</key>
<value>访问通讯录</value>
网友评论