我想在app applicationDidEnterBackground模式下运行此代码。但应用程序无法在后台模式下工作(按主页按钮后)。
func request(urlreq : String,post :String?, completionHandler: @escaping (HTTPURLResponse?,JSON?) -> ()){
let url = NSURL(string: API_URL + urlreq )
let request = NSMutableURLRequest(url: url! as URL)
request.setValue(USER_AGENT, forHTTPHeaderField: "User-Agent")
request.httpMethod = "GET"
if(post != nil){
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = post!.data(using: String.Encoding.utf8)
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
session.dataTask(with: request as URLRequest, completionHandler: { (returnData, response, error) -> Void in
if(returnData != nil)
{
let json = JSON(data: (returnData as NSData!) as Data, error: nil)
completionHandler(response as? HTTPURLResponse,json)
}else{
completionHandler(response as? HTTPURLResponse,nil)
}
}).resume()
}