2017-07-02 27 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

是,我做到了,我再次檢查,而且只是作爲一個澄清,代碼工作,它是被解僱只是沒有。每次。 –