在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.lxweimin.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)
}
}
}
}