[英]Fetch data from Alamofire in background mode
我需要在后台運行應用程序時更新我的應用程序中的訂單。
好吧,我使用OneSignal,我可以得到消息didReceiveRemoteNotification
和里面,我叫Alamofire檢查我的API,我需要更新。
問題是當代碼到達關鍵點時: Alamofire.request(url).responseJSON {(response) in
並沒有進入內部,僅當我打開應用程序時我才能得到結果。
我希望它可以在后台獲取新數據並在更新后通知用戶,因此他們可以單擊通知以查看新內容。
我讀到Alamofire默認在后台線程上運行,但是網絡請求在主線程上進行。
我嘗試了URLSessionConfiguration,但是Error code -999 cancelled.
因此,我在響應的末尾添加了sessionManager.session.finishTasksAndInvalidate()
。 錯誤停止,但是代碼仍然不在Alamofire請求內。
我的一些代碼-AppDelegate上的didReceiveRemoteNotification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let custom = userInfo["custom"] as? NSDictionary {
if let a = custom["a"] as? NSDictionary {
if let update = a["update"] as? NSString {
if update.isEqual(to: "Pedido") {
let strdataPedido = PedidoDAO().getMostRecentDtPedido()
if self.defaults.getDownloadInicialPedido(){
if strdataPedido != "" {
//let task = self.beginBackgroundTask()
self.loadOrdersFromLastSyncByApi(strdataPedido)
//self.endBackgroundTask(task)
}
}
}
}
}
}
我的AppDelegate上的loadOrdersFromLastSyncByApi函數:
func loadOrdersFromLastSyncByApi(_ lastSync: String) {
let parceiroId = defaults.getParceiroId()
PedidoAPI().loadOrdersForLastSync(parceiroId, lastSync){ (dados) in
if let dadosPedidoModel = dados as? [PedidoModel] {
//do what needs to do to save new data
}
PedidoAPI()。loadOrdersForLastSync函數:
func loadOrdersForLastSync(_ parceiroId: String, _ lastSync: String, _ onComplete: @escaping(Any?) -> Void) {
let url = Test.basePath + "/api/orders/parceiro/\(parceiroId)/\(lastSync)"
//let queue = DispatchQueue(label: "com.test.br", qos: .background, attributes: .concurrent)
let task = self.beginBackgroundTask()
let queue = DispatchQueue.global(qos: .background)
queue.async {
Alamofire.request(url).responseJSON {(response) in
//This result its fired just when I open my app, I would like it to make everything on background
switch (response.result) {
//do what needs to send new data
}
self.endBackgroundTask(task)
有什么幫助嗎?
感謝您的提問。 為了澄清,我理解您的問題如下:
當應用程序在后台運行時,您想在用戶訂單發生變化時更新用戶。
后續問題:您是否有理由要從客戶端發出請求? 另外,您不能僅在服務器上處理來自OneSignal的哪些數據?
答:您應該處理服務器上對第三方(Alamofire)的任何請求,然后使用我們的API將請求響應中包含新信息的通知發送給用戶。 我認為這將是最好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.