UIImagePickerController
A view controller that manages the system interfaces for taking pictures, recording movies, and choosing items from the user’s media library.
UIImagePickerController是一个用于拍照、摄像以及从用户媒体库上传图片或视频的管理器。
声明
class UIImagePickerController : UINavigationController
大致介绍
An image picker controller manages user interactions and delivers the results of those interactions to a delegate object. The role and appearance of an image picker controller depend on the source type you assign to it before you present it.
UIImagePickerControlle让用户可以选择图片或视频,并将选择好的对象传递给委托对象上,具体上传哪种多媒体资源并且以何种方式(从媒体库选择还是拍照上传)取决于你规定的source type这个参数。
- UIImagePickerController.SourceType.camera,拍照或录像上传
- UIImagePickerController.SourceType.photoLibrary或UIImagePickerController.SourceType.savedPhotosAlbum,从已保存的图片或视频中选择上传
ps:这些都需要你在Info.plist中设置申请权限,否则不能正常使用:
To use an image picker controller containing its default controls, perform these steps:
要正常使用UIImagePickerControlle,需要做以下几步:
- Verify that the device is capable of picking content from the desired source. Do this by calling the isSourceTypeAvailable(_ : ) class method, providing a constant from the UIImagePickerController.SourceType enumeration.
使用isSourceTypeAvailable方法,sourcetype作为其参数,以此判断设备是否可以获取到指定的资源类型。
if UIImagePickerController.isSourceTypeAvailable(.camera) {
...
}
- Check which media types are available for the source type you’re using, by calling the availableMediaTypes(for:) class method. This lets you distinguish between a camera that can be used for video recording and one that can be used only for still images.
通过使用availableMediaTypes(for:)方法,你可以知道在你指定的sourcetype中你可以获取哪种文件格式,比如相机,就需要区分是录像用的还是拍摄静态图片用的。 - Tell the image picker controller to adjust the UI according to the media types you want to make available—still images, movies, or both—by setting the mediaTypes property.
通过设置mediaTypes参数,你可以选择你需要的文件格式,是静态图片,还是视频,还是都可以。 - Present the user interface. On iPhone or iPod touch, do this modally (full-screen) by calling the present( :animated:completion:) method of the currently active view controller, passing your configured image picker controller as the new view controller.
下面需要显示交互页面,在当前view controller下使用present(_:animated:completion:) 方法,将image picker controller作为一个新的view controller显示出来。 - When the user taps a button to pick a newly-captured or saved image or movie, or cancels the operation, dismiss the image picker using your delegate object. For newly-captured media, your delegate can then save it to the Camera Roll on the device. For previously-saved media, your delegate can then use the image data according to the purpose of your app.
当用户选择好了图像或视频资源,或是点击取消按钮,你需要让image picker消失,回到之前的页面。如若选择好了资源,在回到之前页面后,委托对象应该保存好资源。
提供委托对象
要使用image picker controller你必须提供一个符合UIImagePickerControllerDelegate协议的委托。从iOS 4.1开始,你可以使用委托将静态图像元数据保存到相机中。
调整闪光模式
从iOS 4.0开始,你可以让有闪光灯设备的用户调整闪光模式,选择前置或后置摄像头&#