swift使用系统相册、相机、音视频工具类

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

}

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容