来自用户通知中心的后台模式的Alamofire API调用不工作



我正在应用程序中使用Notification Service Extension实现富通知。单击操作按钮时,我调用API,当应用程序处于前台模式时,该API工作,但当应用程序位于后台模式时,不工作。。我得到了";完成时出现错误[-1005]错误域=NSURLError域代码=-1005";网络连接丢失"我已启用后台提取功能。

以下是我在应用程序代理中的代码

func userNotificationCenter(_center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,带有completionHandler completionHandler:@sescape((->无效({

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")
}
}
}

函数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")
}
})
}
}

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

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

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()
...
}
}

相关内容

  • 没有找到相关文章

最新更新