繁体   English   中英

AVAssetExportSession.requestExportSession 回调从未调用过(swift 3,iOS10)

[英]AVAssetExportSession.requestExportSession callback never called (swift 3, iOS10)

以下代码从不调用导出回调。 导出会话创建得很好。 我没有看到任何错误,也没有任何进展。 CPU 为 0%。 我看没有例外。 状态为 1(进行中),进度为 0,错误为零。 视频在画廊中播放。 我可以成功获得视频的图像。 我已经将代码提取到一个 UIViewController 中进行测试,见下文:

我使用 iOS10.1.1 和我在 iPad 上录制的视频进行了测试。

import UIKit
import Photos

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: Properties
@IBOutlet weak var button: UIButton!

// MARK: Actions
@IBAction func onPress(_ sender: UIButton) {
    requestGalleryPermission() {
        (_ hasPermission: Bool) in
        if hasPermission {
            // fetch the asset from Photos
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: ["9FFAD8B5-0941-4A95-830F-4ACFA563B71B/L0/001"], options: nil)

            // if we successfully fetched the asset...
            if let asset = fetchResult.firstObject {

                self.exportAsset(asset)
            }
        }
    }
}

func exportAsset(_ asset: PHAsset) {
    let tempFilename = "full_sized_image.mov"
    var tempURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(tempFilename)
    tempURL = tempURL.standardizedFileURL


    let options = PHVideoRequestOptions()
    options.deliveryMode = .highQualityFormat
    options.isNetworkAccessAllowed = true

    // remove any existing file at that location
    do {
        try FileManager.default.removeItem(at: tempURL)
    }
    catch {
        // most likely, the file didn't exist.  Don't sweat it
    }

    PHImageManager.default().requestExportSession(forVideo: asset, options: options, exportPreset: AVAssetExportPresetHighestQuality) {
        (exportSession: AVAssetExportSession?, _) in

        if exportSession == nil {
            print("COULD NOT CREATE EXPORT SESSION")
            return
        }

        exportSession!.outputURL = tempURL
        exportSession!.outputFileType = AVFileTypeQuickTimeMovie

        print("GOT EXPORT SESSION")
        exportSession!.exportAsynchronously() {
            print("COMPLETION HANDLER!!!!")
        }

        print("progress: \(exportSession!.progress)")
        print("error: \(exportSession!.error)")
        print("status: \(exportSession!.status.rawValue)")
    }
}

func requestGalleryPermission(_ completionHandler: @escaping (_ hasPermission: Bool) -> Void) {

    let authorizationStatus = PHPhotoLibrary.authorizationStatus()
    if authorizationStatus == .denied || authorizationStatus == .restricted {
        completionHandler(false)
    }
    else if authorizationStatus == .authorized {
        completionHandler(true)
    }
    else {
        // ask for authorization
        PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) in

            // if the user gave us authorization...
            if status == .authorized {

                print("User gave authorization")

                completionHandler(true)
            }
            else {
                print("User denied authorization")

                completionHandler(false)
            }
        })
    }
}
}

Swift 3对我来说就像一个魅力!

func exportVideoAsset(_ asset: PHAsset) {
    let filename = UUID().uuidString.appending(".mp4") // setting random file name

    let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    do {
        var fileurl = try documentsUrl.absoluteString.appending(filename).asURL()
        print("exporting video to ", fileurl)
        fileurl = fileurl.standardizedFileURL


        let options = PHVideoRequestOptions()
        options.deliveryMode = .highQualityFormat
        options.isNetworkAccessAllowed = true

        // remove any existing file at that location
        do {
            try FileManager.default.removeItem(at: fileurl)
        }
        catch {
            // most likely, the file didn't exist.  Don't sweat it
        }

        PHImageManager.default().requestExportSession(forVideo: asset, options: options, exportPreset: AVAssetExportPresetHighestQuality) {
            (exportSession: AVAssetExportSession?, _) in

            if exportSession == nil {
                print("COULD NOT CREATE EXPORT SESSION")
                return
            }

            exportSession!.outputURL = fileurl
            exportSession!.outputFileType = AVFileTypeMPEG4 //file type encode goes here, you can change it for other types

            print("GOT EXPORT SESSION")
            exportSession!.exportAsynchronously() {
                 print("EXPORT DONE")
            }

            print("progress: \(exportSession!.progress)")
            print("error: \(exportSession!.error)")
            print("status: \(exportSession!.status.rawValue)")
        }
    }
    catch {
        // something may happend here, like no disk space
    }
}

有时 iOS 会导致AVAssetExportSession的状态卡在.waiting

这似乎发生在几次失败的导出尝试之后。 后续的导出永远不会开始。

重新启动设备会清除导出队列并通常可以解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM