testfairy-blog / VideoCompressionTutorial

iOS - Fine tuned video compression in Swift 4

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Compression fail in Background

Mahan3340 opened this issue · comments

commented

When the app enters background, the compression continues for few seconds with low GPU priority and then it stops and after entering the app again the compression will fail with below error :

Error: Error Domain=AVFoundationErrorDomain Code=-11847 "Operation Interrupted" UserInfo={NSLocalizedRecoverySuggestion=Stop other operations and try again., NSLocalizedDescription=Operation Interrupted, NSUnderlyingError=0x2806c07e0 {Error Domain=NSOSStatusErrorDomain Code=-16121 "(null)"}}

I'm using swift 4 and ios 12.2 both simulator and iphone 6s tested

write UIApplication.shared.beginBackgroundTask {}

after closures. after task executed you have to end the background task otherwise apple will terminate your app.

commented

@sinhaGIT where to add this line ?

Hi everyone, maintainer here. Just like @Tulakshana stated, the code below can be used to properly initiate a task in the background. I'm pasting it here to make it more accessible for future readers.

// Perform the task on a background queue.
DispatchQueue.global().async {
    // Request the task assertion and save the ID.
    self.backgroundTaskID = UIApplication.shared.beginBackgroundTask (withName: "Finish Network Tasks") {
        // End the task if time expires.
        cancelable.cancel = true
        UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
        self.backgroundTaskID = UIBackgroundTaskInvalid
    }
            
    self.cancelable = compressh264VideoInBackground(
        videoToCompress: videoToCompress,
        destinationPath: destinationPath,
        size: nil, // nil preserves original,
        //size: (width: 1280, height: 720) 
        compressionTransform: .keepSame,
        compressionConfig: .defaultConfig,
        completionHandler: { path in
            // use path to store it somewhere or send to a server

            UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
            self.backgroundTaskID = UIBackgroundTaskInvalid
        },
        errorHandler: { e in
            print("Error: ", e)
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
            self.backgroundTaskID = UIBackgroundTaskInvalid
        },
        cancelHandler: {
            print("Canceled.")
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
            self.backgroundTaskID = UIBackgroundTaskInvalid
        }
    )
}

In this piece of code, self.backgroundTaskID and self.cancelable are instance variables you store in the class initiates this code. They can be globals if this task is planned to be a singleton.