iOS: Firebase Storage set timeout

2019-07-22 06:04发布

when downloading from storage, I would like to set a smaller timeout, e.g. only 5 - 10 seconds, is this possible?

I'm downloadiung like this:

        let storage = FIRStorage.storage()
        let storageRef = storage.reference(forURL: "gs://...")
        let fileRef = storageRef.child(myLink)
        let downloadTask = fileRef.write(toFile: url) { url, error in
        ...

2条回答
Viruses.
2楼-- · 2019-07-22 06:23

I would make a extension to the StorageDownloadTask class and add a function that sets a timer with the requested time that cancels the request if fired.

Something like this:

extension StorageDownloadTask {
func withTimout(time: Int, block: @escaping () -> Void) {
    Timer.scheduledTimer(withTimeInterval: TimeInterval(time), repeats: false) { (_) in
        self.cancel()
        block()
    }
}

So you would write:

fileRef.write(toFile: url, completion: {
    (url, error) in
    ...
}).withTimeout(time: 10) {
    //Here you can tell everything that needs to know if the download failed that it did
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-22 06:31

Firebase Storage has a feature where you can pause(), cancel(), and resume() read here

I would set a class property as StorageUploadTask then I would put the pause or cancel in a DispatchAsync Timer using a DispatchWorkItem:

// 1. make sure you `import Firebase` to have access to the `StorageUploadTask`
import Firebase

var timeoutTask: DispatchWorkItem?
var downloadTask: StorageUploadTask?

// using your code from your question
let storage = FIRStorage.storage()
let storageRef = storage.reference(forURL: "gs://...")
let fileRef = storageRef.child(myLink)

// 2. this cancels the downloadTask
timeoutTask = DispatchWorkItem{ [weak self] in
          self?.downloadTask?.cancel()
}

// 3. this executes the code to run the timeoutTask in 5 secs from now. You can cancel this from executing by using timeoutTask?.cancel() 
DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: timeoutTask!)

// 4. this initializes the downloadTask with the fileRef your sending the data to
downloadTask = fileRef.write(toFile: url) { 
          (url, error) in

          self.timeoutTask?.cancel() 
          // assuming it makes it to this point within the 5 secs you would want to stop the timer from executing the timeoutTask

          self.timeoutTask = nil // set to nil since it's not being used
 }

Unfortunately Firebase doesn't have this feature available for the RealTimeDatabase

查看更多
登录 后发表回答