拍照上传
虚拟机无法获取摄像头,需真机调试
(1)Info.plist配置
由于苹果安全策略更新,在使用Xcode8开发时,需要在Info.plist配置请求照片相的关描述字段(Privacy - Photo Library Usage Description),(Privacy - Camera Usage Description)
import UIKit
import Photos
import AVFoundation
import MobileCoreServices
import CryptoSwift
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var takephotos: [UIButton]!
@IBAction func openCamera(){
//打开相册
let pickImageController:UIImagePickerController=UIImagePickerController.init()
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
//获取相册权限
PHPhotoLibrary.requestAuthorization({ (status) in
switch status {
case .notDetermined: break
case .restricted://此应用程序没有被授权访问的照片数据
break
case .denied://用户已经明确否认了这一照片数据的应用程序访问
break
case .authorized://已经有权限
break
}
})
}
//打开相机拍照
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (ist) in
let status:AVAuthorizationStatus=AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status==AVAuthorizationStatus.authorized {//获得权限
//跳转到相机或者相册
pickImageController.delegate=self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
pickImageController.allowsEditing = true
pickImageController.sourceType = UIImagePickerControllerSourceType.camera;
//弹出相册页面或相机
self.present(pickImageController, animated: true, completion: {
})
}else if (status==AVAuthorizationStatus.denied)||(status==AVAuthorizationStatus.restricted) {
}
})
}
}
func gotoSetting(){
let alertController:UIAlertController=UIAlertController.init(title: "去设置", message: "设置-》通用-》", preferredStyle: UIAlertControllerStyle.alert)
let sure:UIAlertAction=UIAlertAction.init(title: "去开启权限", style: UIAlertActionStyle.default) { (ac) in
let url=URL.init(string: UIApplicationOpenSettingsURLString)
if UIApplication.shared.canOpenURL(url!){
UIApplication.shared.open(url!, options: [:], completionHandler: { (ist) in
})
}
}
alertController.addAction(sure)
self.present(alertController, animated: true) {
}
}
//图片上传代码内容,请参考相册上传
photopost
作者:刘俊龙
信息录入:刘俊龙