2017-07-02 31 views
0

失败,我是相当新的SWIFT(1周)和iOS编程,我的问题是,我似乎错过了一些基本的了解。在下面你看到一个由后台通知触发的函数。我可以和已验证我收到的背景通知可靠和应用程序来(控制台上的原始数据值的打印输出)有效,只要应用程序是在前台一切工作,正如预期的,它就会被解雇,并发送一个https请求。背景触发器每分钟都有一个计时器。迅速3+,URLsession,在后台显然随机

现在,当应用程序进入后台整个事情的变化。在这种情况下,我仍然通过通知(控制台打印输出)获得触发器,并且我可以在调试器中看到与前景中的魅力发生作用相同的功能。它仍然有效,它仍然被解雇,但数据包只是经常发送,随机发送,看起来在2到30分钟之间。

let config = URLSessionConfiguration.background(withIdentifier: "org.x.Reporter") 
class queryService { 
    let defaultSession = URLSession(configuration: config) 
    var dataTask: URLSessionDataTask? 


    var errorMessage = "" 


    func getSearchResults(baseURL: String, searchTerm: String) { 
     dataTask?.cancel() 
     config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData; 
     config.timeoutIntervalForRequest = 10 

     if var urlComponents = URLComponents(string: "https://host.com/reportPosition.php") { 
      urlComponents.query = "\(searchTerm)" 
      guard let url = urlComponents.url else { return } 

      dataTask = defaultSession.dataTask(with: url) 
     } 
     // 7 
     dataTask?.resume() 
    } 
} 

回答

0

尝试使用dataTaskWithCompletion,以便您可以看到错误中出现了什么问题。

URLSession.shared.dataTask(with: URL.init(string: "")!) { (data, response, error) in 
     if error != nil { 
      // Error 
     } 
    }.resume() 

https://developer.apple.com/documentation/foundation/urlsession/1410330-datatask

编辑

你想要做的是什么背景,你通过delegate电话获得completions备份,所以当你init乌尔URLSession这样做使用以下func

URLSession.init(configuration: URLSessionConfiguration.init(), delegate: self, delegateQueue: OperationQueue.init()) 

https://developer.apple.com/documentation/foundation/urlsession/1411597-init

然后符合乌尔班到URLSessionDelegate像这样

class queryService, URLSessionDelegate { 

然后实现此处所列呼叫的delegate方法备份

https://developer.apple.com/documentation/foundation/urlsessiondelegate

EDIT2

这里感伤它 https://www.raywenderlich.com/158106/urlsession-tutorial-getting-started

+0

d教程中,我其实是有这个第一,但iOS的告诉我,在后台,你不能有一个完成处理程序: “异常‘NSGenericException’,理由是:“完成处理程序块不会在后台支持会话。使用委托来代替。” –

+0

权。是否启用'背景Fetch'该项目的'Capabilities'选项下。https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started –

+0

是,我做到了,我再次检查,而且只是作为一个澄清,代码工作,它是被解雇只是没有。每次。 –