2017-04-13 250 views
1

從存儲下載時,我想設置一個較小的超時時間,例如,只有5 - 10秒,這可能嗎?iOS:Firebase存儲設置超時時間

我downloadiung這樣的:

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

回答

0

我會做一個延伸到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()閱讀here

我會成立一個類屬性爲StorageUploadTask然後我會暫停或ca NCEL在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 
} 

不幸的是火力地堡沒有可用於RealTimeDatabase

此功能