iOS:Firebase 存储设置超时

问题描述 投票:0回答:3

从存储下载时,我想设置一个较小的超时时间,例如只有 5 - 10 秒,这可能吗?

我是这样下载的:

        let storage = FIRStorage.storage()
        let storageRef = storage.reference(forURL: "gs://...")
        let fileRef = storageRef.child(myLink)
        let downloadTask = fileRef.write(toFile: url) { url, error in
        ...
ios swift3 firebase-storage
3个回答
1
投票

我将对 StorageDownloadTask 类进行扩展并添加一个函数,该函数设置一个具有请求时间的计时器,如果触发则取消请求。

像这样的东西:

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

所以你会写:

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
}

0
投票

Firebase Storage
有一个功能,您可以在其中
pause()
cancel()
resume()
阅读这里

我会将类属性设置为

StorageUploadTask
然后我会使用
DispatchAsync Timer
:
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
 }

不幸的是,Firebase 没有可用于

RealTimeDatabase

的此功能

0
投票

FIRStorage
(更名为
Storage
)现在建议您可以使用的超时变量:

let storage = Storage.storage()
storage.maxUploadRetryTime = 10
storage.maxOperationRetryTime = 10
storage.maxDownloadRetryTime = 10
...
© www.soinside.com 2019 - 2024. All rights reserved.