用到的第三方庫:
Alamofire 用于網(wǎng)絡(luò)請求和視頻下載
MobilePlayer 用于播放在線視頻
創(chuàng)建Movie類:
import Foundation
import Alamofire
class Movie {
private var url: NSURL //網(wǎng)絡(luò)路徑 如果本地路徑存在則是本地路徑
init (url: NSURL) {
self.url = url
}
//獲取播放路徑
func getUrl() -> NSURL {
if isExist() {
let url = NSURL(fileURLWithPath: getFilePath())
return url
}
return self.url
}
//通知下載 如果已經(jīng)存在 不下載
func postDownload() {
if isExist() {
return
}
let destination = Alamofire.Request.suggestedDownloadDestination()
Alamofire.download(.GET, url, destination: destination).response { _, _, _, error in
if let error = error {
print("Failed with error: \(error)")
} else {
print("Downloaded file successfully")
}
}
}
//是否已經(jīng)下載
private func isExist() -> Bool{
let fileManager = NSFileManager.defaultManager()
let filePath = getFilePath()
print(filePath)
let exist = fileManager.fileExistsAtPath(filePath)
return exist
}
//通過文件名稱 獲取文件路徑
private func getFilePath() -> String {
let filePath = NSHomeDirectory() + "/Documents/" + getFileName()
return filePath
}
//通過url 獲取文件名稱
private func getFileName() -> String {
let array = self.url.URLString.componentsSeparatedByString("/")
return array.last!
}
}
創(chuàng)建Movie對象:
let string = "視頻路徑"
let url = NSURL(string: string)!
let movie = Movie(url: url)
movie.postDownload() //下載
play(movie)//播放
播放方法:
import MobilePlayer
func play(movie: Movie) {
let url = movie.getUrl()
let playerVC = MobilePlayerViewController(contentURL: url)
playerVC.activityItems = [url]
presentMoviePlayerViewControllerAnimated(playerVC)
}
一邊播放一遍下載捍歪,下載成功后會播放本地路徑的視頻掘鄙。
清除所有緩存:
//清除所有緩存
func cleanAllCache() {
let fileManager = NSFileManager.defaultManager()
let myDirectory = NSHomeDirectory() + "/Documents"
let fileArray:[AnyObject]? = fileManager.subpathsAtPath(myDirectory)
for fn in fileArray!{
try! fileManager.removeItemAtPath(myDirectory + "/\(fn)")
}
}
這里是用的是Alamofire設(shè)置的下載路徑滔驾,注意刪除的路徑要和下載的路徑一致缕陕。
//獲取所有緩存大小
func getAllCacheSize() -> String {
let fileManager = NSFileManager.defaultManager()
let myDirectory = NSHomeDirectory() + "/Documents"
let fileArray:[AnyObject]? = fileManager.subpathsAtPath(myDirectory)
var allSize = 0.0
for fn in fileArray!{
let attr = try! fileManager.attributesOfItemAtPath(myDirectory + "/\(fn)")
let size = (attr["NSFileSize"] as! Double) / 1000000 //單位為 M
allSize += size
}
return String(format: "%.1f", allSize) //保留小數(shù)點后一位
}