您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

Swift 共享檔案操作整理(iOS 8 以上)

編輯:iOS 相關教學

前言

這篇筆記整理在 iOS 8 以上版本中,如何讓 App 開放檔案共享、讀取共享目錄裡的影片、播放、用其他 App 開啟、刪除,以及存回相簿。適合需要讓使用者從 iTunes 或檔案 App 丟檔案進來的情境。

正文

一、前置準備

1. 打開檔案共享

App 預設是不開放檔案共享的,需要在 plist 中把 Application supports iTunes file sharing 設為 YES。設定完成後把裝置連上 iTunes,就能在 App 的「檔案共享」區塊看到你的應用程式(若沒出現,把傳輸線拔插一次即可)。這時可以丟幾支影片進去,方便後續測試。

2. 匯入所需框架

Photos.framework 用於相簿操作,AVKit.framework 則負責影片播放。

二、取得影片清單

private let VIDEO_EXTENSIONS = [".MOV", ".MP4"]
private var fileManager = NSFileManager.defaultManager()

func loadVideos() {
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    if paths.count > 0 {
        let documentsDirectory = paths[0] as String
        let documentUrl = NSURL(fileURLWithPath: documentsDirectory, isDirectory: true)
        do {
            let files = try fileManager.contentsOfDirectoryAtPath(documentsDirectory)
            for file in files {
                fetchVideos(documentUrl.URLByAppendingPathComponent(file).path ?? "")
            }
        } catch { }
        self.tableView.reloadData()
    }
}

func fetchVideos(path: String) {
    var isDir: ObjCBool = false
    if !path.isEmpty && fileManager.fileExistsAtPath(path, isDirectory: &isDir) {
        if isDir {
            do {
                let files = try fileManager.contentsOfDirectoryAtPath(path)
                for file in files { fetchVideos(file) }
            } catch { }
        } else {
            var file = File(path: path)
            if file.isValid() && isVideoFileExtension(file.fileExtension.uppercaseString) {
                do {
                    if let attr: NSDictionary = try fileManager.attributesOfItemAtPath(path) {
                        file.fileSize = attr.fileSize()
                    }
                } catch { }
                videos.append(file)
            }
        }
    }
}

func isVideoFileExtension(ext: String) -> Bool {
    for videoExtension in VIDEO_EXTENSIONS {
        if ext == videoExtension { return true }
    }
    return false
}

struct File {
    var fileExtension = ""
    var fileName = ""
    var path = ""
    var assert: AVURLAsset?
    var url: NSURL!
    var fileSize: UInt64 = 0

    init(path: String) {
        self.path = path
        self.url = NSURL(fileURLWithPath: path)
        self.fileName = url.lastPathComponent ?? ""
        self.fileExtension = "." + (url.pathExtension ?? "")
    }

    func isValid() -> Bool {
        return !(fileName.isEmpty || fileExtension.isEmpty)
    }
}

程式碼說明:

a)注意 Swift 的呼叫方式,例如 fileExistsAtPath 的第二個參數是 inout,傳入時要帶 &。

b)pathExtension 與 lastPathComponent 在 Swift 這一代已經從 NSString/String 移到 NSURL 上,網路上不少教學還停留在舊寫法,直接複製容易編譯不過。

c)影片長度可以這樣取:CMTimeGetSeconds(AVURLAsset(URL: file.url, options: nil).duration)。

三、播放影片

func play(file: File) {
    let player = AVPlayer(URL: file.url)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.presentViewController(playerViewController, animated: true) {
        playerViewController.player?.play()
    }
}

四、用其他 App 開啟

func openIn(file: File, indexPath: NSIndexPath) {
    let document = UIDocumentInteractionController(URL: file.url)
    let rect = self.tableView.rectForRowAtIndexPath(indexPath)
    document.presentOpenInMenuFromRect(rect, inView: self.tableView, animated: true)
}

五、刪除檔案

func delete(file: File, indexPath: NSIndexPath) {
    do {
        try fileManager.removeItemAtPath(file.path)
        videos.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    } catch { }
}

六、存回相簿

func saveToCameraRoll(file: File, indexPath: NSIndexPath) {
    if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file.path) {
        UISaveVideoAtPathToSavedPhotosAlbum(file.path, self,
            "image:didFinishSavingWithError:contextInfo:", nil)
    } else {
        // 不支援,保存失敗
    }
}

func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer,
           contextInfo: UnsafePointer<Void>) {
    if error == nil {
        // 保存成功
    } else {
        // 保存失敗
    }
}

程式碼說明:

使用 UISaveVideoAtPathToSavedPhotosAlbum 時,第三個參數的 Selector 字串必須與你實作的方法簽名完全一致,寫錯一個字元就會在執行期崩潰,而且錯誤訊息通常不夠明確,建議先對著一次。

以上就是 iOS 8 共享檔案的實作範例,需要的朋友可以作為起點,再依自己的業務調整副檔名白名單與錯誤處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved