在IOS开发中经常会用到系统相册,相机,音视频等功能。每次都写比较麻烦,自己封装了一个工具类,实现一句话调用系统相册,相机,音视频等功能。方便以后项目的开发。
//加载图片
SystemTool.shareTool.choosePicture(self, editor: false) { (image) in
button.setImage(image, for: UIControlState.normal)
}
//加载视频
//http://baobab.wdjcdn.com/14562919706254.mp4
SystemTool.playVideoWithPath(video: "apple.mp4", viewController: self)
//加载音乐
SystemTool.playAudioWithPath(sound: "song.mp3")
//停止音乐
SystemTool.stopAudioPlayer()
本文附上swift版代码:(PS:OC版见链接www.jianshu.com/p/6244c1179369)
//// Tool.swift// QRCode//// Created by gaofu on 16/9/9.// Copyright © 2016年 gaofu. All rights reserved.//import UIKitimport AVKitimport AVFoundationimport CoreLocationstruct PhotoSource:OptionSet{ let rawValue:Int static let camera = PhotoSource(rawValue: 1) static let photoLibrary = PhotoSource(rawValue: 1<<1) }//http://10.10.12.124/SVN_Project/YiEr_App/pages/example.htmlfunc <(lhs: T?, rhs: T?) -> Bool{ switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false }}func >(lhs: T?, rhs: T?) -> Bool
{
switch (lhs, rhs)
{
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
typealias finishedImage = (_ image:UIImage) -> ()
typealias cityName = (_ name:String) -> ()
//var audioPlayer = AVAudioPlayer()//定义全局
var audioPlayer : AVAudioPlayer?
var playViewController = AVPlayerViewController()
var videoPlayer = AVPlayer()
class SystemTool: NSObject
{
//MARK: - 1.单例
static let shareTool = SystemTool()
private override init() {}
var finishedImg : finishedImage?
var cityName : cityName?
var isEditor = false
//定位管理器
var locationManager = CLLocationManager()
//MARK: - 2.选择图片
func choosePicture(_ controller : UIViewController, editor : Bool,options : PhotoSource = [.camera,.photoLibrary], finished : @escaping finishedImage)
{
finishedImg = finished
isEditor = editor
if options.contains(.camera) && options.contains(.photoLibrary)
{
let alertController = UIAlertController(title: "请选择图片", message: nil, preferredStyle: .actionSheet)
let photographAction = UIAlertAction(title: "拍照", style: .default) { (_) in
self.openCamera(controller: controller, editor: editor)
}
let photoAction = UIAlertAction(title: "从相册选取", style: .default) { (_) in
self.openPhotoLibrary(controller: controller, editor: editor)
}
let cannelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alertController.addAction(photographAction)
alertController.addAction(photoAction)
alertController.addAction(cannelAction)
controller.present(alertController, animated: true, completion: nil)
}
else if options.contains(.photoLibrary)
{
self.openPhotoLibrary(controller: controller, editor: editor)
}
else if options.contains(.camera)
{
self.openCamera(controller: controller, editor: editor)
}
}
///打开相册
func openPhotoLibrary(controller : UIViewController, editor : Bool)
{
let photo = UIImagePickerController()
photo.delegate = self
photo.sourceType = .photoLibrary
photo.allowsEditing = editor
controller.present(photo, animated: true, completion: nil)
}
///打开相机
func openCamera(controller : UIViewController, editor : Bool)
{
guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
let photo = UIImagePickerController()
photo.delegate = self
photo.sourceType = .camera
photo.allowsEditing = editor
controller.present(photo, animated: true, completion: nil)
}
//MARK: - 3.确认弹出框
class func confirm(title:String?,message:String?,controller:UIViewController,handler: ( (UIAlertAction) -> Swift.Void)? = nil)
{
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let entureAction = UIAlertAction(title: "确定", style: .destructive, handler: handler)
alertVC.addAction(entureAction)
controller.present(alertVC, animated: true, completion: nil)
}
//停掉音频
class func stopAudioPlayer() {
guard let temAudioPlayer = audioPlayer else {
return
}
temAudioPlayer.stop()
}
//MARK: - 4.播放声音
class func playAudioWithPath(sound:String)
{
var url:URL?
if sound.hasPrefix("http"){//远程的地址
url = URL.init(string: sound)
}else{//本地的路径
guard let soundPath = Bundle.main.path(forResource: sound, ofType: nil) else {
NSLog("没找到相关音频")
return
}
url = URL.init(fileURLWithPath: soundPath)
}
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer.init(contentsOf: url!)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}catch let audioError as NSError{
NSLog(audioError.debugDescription)
}
}
//MARK: - 5.播放视频
class func playVideoWithPath(video:String,viewController:UIViewController)
{
var url:URL?
if video.hasPrefix("http"){//远程的地址
url = URL.init(string: video)
}else{//本地的路径
guard let videoPath = Bundle.main.path(forResource: video, ofType: nil) else {
NSLog("没找到相关视频")
return
}
url = URL.init(fileURLWithPath: videoPath)
}
videoPlayer = AVPlayer.init(url: url!)
playViewController.player = videoPlayer
/*
可以设置的值及意义如下:
AVLayerVideoGravityResizeAspect 不进行比例缩放 以宽高中长的一边充满为基准(defult)
AVLayerVideoGravityResizeAspectFill 不进行比例缩放 以宽高中短的一边充满为基准
AVLayerVideoGravityResize 进行缩放充满屏幕
*/
playViewController.videoGravity = AVLayerVideoGravityResizeAspect
viewController.present(playViewController, animated: true) {
playViewController.player?.play()
}
}
//MARK: - 6.定位城市功能
func locationManagerWithCity(city:@escaping cityName) {
cityName = city
//检测定位功能是否开启
if CLLocationManager.locationServicesEnabled() {
//定位,获取城市
locationManager.delegate = self
//设置定位精度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//更新距离
locationManager.distanceFilter = 100
//发送授权申请
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
//允许使用定位服务的话,开启定位服务更新
locationManager.startUpdatingLocation()
NSLog("定位开始")
}
}else{
NSLog("没有开启定位功能")
}
}
}
//由于 AVPlayerViewController 不能被继承,如果你想要实现只支持横屏播放的话,可以考虑用 extension :
//extension AVPlayerViewController {
// override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// return .landscapeLeft
// }
//}
//MARK: - CLLocationManagerDelegate
//MARK: - UIImagePickerControllerDelegate
extension SystemTool : UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate
{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
guard let image = info[isEditor ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage] as? UIImage else { return }
picker.dismiss(animated: true) { [weak self] in
guard let tmpFinishedImg = self?.finishedImg else { return }
tmpFinishedImg(image)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
picker.dismiss(animated: true, completion: nil)
}
//MARK: - CLLocationManangerDelegate 定位改变执行,可以得到新位置、旧位置
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
//获取最新的坐标
let currLocation:CLLocation = locations.last!
self.reverseGeocoder(currentLocation: currLocation)
NSLog("精度\(currLocation.coordinate.longitude),纬度\(currLocation.coordinate.latitude)")
}
//MARK: 反地理编码
func reverseGeocoder(currentLocation:CLLocation) {
let geocoder = CLGeocoder.init()
geocoder.reverseGeocodeLocation(currentLocation) { (placemarks, error) in
if (error != nil)||placemarks?.count==0{
NSLog(error.debugDescription)
}else{
let placemark:CLPlacemark = (placemarks?.first)!
let name = placemark.addressDictionary?["City"]
guard let tmpCityName = self.cityName else { return }
tmpCityName(name as! String)
}
}
}
}