0
votes

I am implementing Rich notifications using Notification Service Extension in my app. On click of action button i am calling an API which is working when app is in foreground mode but not working when app is in background mode.. I am getting "finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." I have enabled background fetch in capabailities.

Below is my code in App delegate

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")
            }
      })
   }
}
1
Did you resolve it? I have the same problemAlejandro Henriquez

1 Answers

1
votes

The system is taking down the network connection when you call the completion handler.

You should pass the completion handler from userNotificationCenter(_:didReceive:withCompletionHandler:) to your func and call it when the process has ended something like this

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