【问题标题】:Alamofire API call from background mode from userNotificationCenter not working从 userNotificationCenter 的后台模式调用 Alamofire API 不起作用
【发布时间】:2021-01-31 14:54:01
【问题描述】:

我正在我的应用中使用通知服务扩展来实现丰富的通知。单击操作按钮时,我正在调用一个 API,该 API 在应用程序处于前台模式时工作,但在应用程序处于后台模式时不工作.. 我收到“以错误结束 [-1005] 错误域 = NSURLErrorDomain 代码 = -1005 “网络连接丢失。”我已启用后台获取功能。

下面是我在 App 委托中的代码

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {

    defer {
        completionHandler()
    }
       let userInfo = response.notification.request.content.userInfo
       print("userinfo : \(userInfo)")
       if let aps = userInfo[AnyHashable("aps")] as? NSDictionary, let device_id = aps["device_id"] as? NSNumber
       {
          UserDefaults.standard.set(device_id.stringValue, forKey: "deviceID")
          print("action identifier is :\(response.actionIdentifier)")
          switch response.actionIdentifier {
          case "VIEW":
          print("view")
          self.apiCall()
          case UNNotificationDismissActionIdentifier:
          print("second")
          default:
          print("default")
        }
       }
}

func apiCall() {

    if let domain_name = UserDefaults.standard.value(forKey: DOMAIN_NAME) as? String, let device_id = UserDefaults.standard.value(forKey: "deviceID") as? String
    {
        let hash_key = UserDefaults.standard.value(forKey: LoginKey) as! String
        let user_name = UserDefaults.standard.value(forKey: USER_NAME) as! String
        let url = domain_name + "/abc.php"
        let parameters : Dictionary<String, Any> = [
            "action" : "xyz",
            "user_name" : user_name,
            "hash_key" : hash_key,
            "parking_status": "0",
            "latitude":0,
            "longitude" : 0,
            "device_id": device_id
        ]
        print("parking set URL: \(url), parameters:\(parameters)")
        
        APIManager.sharedInstance.CallNewTrackResult(urlString: url, parameters: parameters, completionHandler: {data, r_error, isNetwork in
            if isNetwork{
                let result = data?[K_Result] as? Int ?? 100
                switch (result){
                case 0 :
                    if let message = data?[K_Message] as? String
                    {
                        print("parking message is :\(message)")
                        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
                        let actionYes = UIAlertAction(title: "OK", style: .default, handler: { action in
                        })
                        alert.addAction(actionYes)
                        DispatchQueue.main.async {
                        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
                        }
                    }
                    break
                case _ where result > 0 :
                    let message = data?[K_Message] as! String
                    print(message)
                    break
                default:
                    print("Default Case")
                }
            }else{
                //showToast(controller: self, message: "Please check your Internet Connection.", seconds: 0.3)
                print("ERROR FOUND")
            }
      })
   }
}

【问题讨论】:

  • 你解决了吗?我有同样的问题

标签: ios push-notification notifications alamofire background-fetch


【解决方案1】:

当您调用完成处理程序时,系统正在断开网络连接。

您应该将完成处理程序从 userNotificationCenter(_:didReceive:withCompletionHandler:) 传递给您的 func 并在进程结束时调用它

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
   apiCall(completion: completionHandler)
}

func apiCall(completion: () -> Void) {
  ...
  APIManager.sharedInstance.CallNewTrackResult(urlString: url, parameters: parameters, completionHandler: {data, r_error, isNetwork in
     completion()
     ...
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2019-06-09
    • 2017-02-22
    • 1970-01-01
    • 2019-07-25
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多