iOS:Firebase存储设置超时

t3psigkw  于 2023-03-31  发布在  iOS
关注(0)|答案(3)|浏览(140)

当从存储下载时,我想设置一个较小的超时,例如只有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
        ...
vfwfrxfs

vfwfrxfs1#

我将对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
}
llycmphe

llycmphe2#

Firebase Storage有一个特性,您可以在此处阅读pause()cancel()resume()
我会将一个类属性设置为StorageUploadTask,然后我会使用DispatchWorkItem将暂停或取消放在DispatchAsync Timer中:

// 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的此功能

pb3s4cty

pb3s4cty3#

FIRStorage(重命名为Storage)现在提供了可以使用的超时变量:

let storage = Storage.storage()
storage.maxUploadRetryTime = 10
storage.maxOperationRetryTime = 10
storage.maxDownloadRetryTime = 10
...

相关问题