应用程序进入后台模式时服务调用失败

Service call fails when app goes into background mode

已在 DispatchQueue.global qos.background 模式下调用服务。

    override func viewDidLoad() {
        super.viewDidLoad()  
  DispatchQueue.global(qos: .background).async {
        self.modelClass.fetchData(page: self.pageCount){
            DispatchQueue.main.async {
                self.tbl_View.reloadData()
            }
        }
    }
}

// 视图模型

func fetchData(page: Int, completion: @escaping () -> ()){
    let urlString = "ServiceURL"
    ClientModel.getDataLists(urlString: urlString) { DataModel in
        DispatchQueue.main.async {
            self.delegate?.reloadTableData()
        }
        completion()
    }
}

// 客户端模型

func getDataLists(urlString: String, completion: @escaping ([DataModel]) -> ()){

    guard let url = URL(string: urlString) else { return }
    var request = URLRequest(url: url)
    request.httpMethod = RequestType.get
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")

       let task = URLSession.shared.DataModelTask(with: url) { dataModel, response, error in
    if error != nil || dataModel == nil {
        print("Client error!")
        return
    }
         if let dataModel = dataModel {
            completion([dataModel])
        }
    }

    task.resume()
}

调用服务调用后,立即打开另一个应用程序,服务调用没有得到响应。

调用服务调用后应用程序进入后台模式时如何获得响应?

尝试使用以下代码。示例代码在这里:https://github.com/achuaswani/iTunesSearchExample.git

var taskeid = UIBackgroundTaskIdentifier.invalid
taskeid = UIApplication.shared.beginBackgroundTask {
      let ti = taskeid
      taskeid = UIBackgroundTaskIdentifier.invalid
      if ti != UIBackgroundTaskIdentifier.invalid {
         UIApplication.shared.endBackgroundTask(ti)
       }
}

//Your service call
//End the background task after getting the response
let ti = taskIdentifier
taskeid = UIBackgroundTaskIdentifier.invalid
if ti != UIBackgroundTaskIdentifier.invalid {
     UIApplication.shared.endBackgroundTask(ti)
 }