私は今ここにいます。それは完璧ではありませんが、おそらく時間の半分で動作します。
まず、私のURLsessionが定義されているクラスで:
import Foundation
class Central: NSObject, URLSessionDataDelegate, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate {
私はそれがそこにすべてのことが必要であると思いますが、しないでください。そして、ここで私のバックグラウンドによって呼び出される関数がフェッチされます。
func getWebData() {
var defaults: UserDefaults = UserDefaults.standard
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myBGconfig")
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
urlString = "https://www.powersmartpricing.org/psp/servlet?type=dayslider"
if let url = URL(string: urlString) {
let rateTask = backgroundSession.downloadTask(with: URL(string: urlString)!)
rateTask.taskDescription = "rate"
rateTask.resume()
}
をタスクが戻って来るとき:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if downloadTask.taskDescription == "rate" { // I run 2 web tasks during the session
if let data = NSData(contentsOf: location) {
var return1 = String(data: data as! Data, encoding: String.Encoding.utf8)!
DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + 0.2){
var defaults: UserDefaults = UserDefaults.standard
defaults.set(myNumber, forKey: "electricRate") // myNumber is an extract of the text in returned web data
defaults.set(Date(), forKey: "rateUpdate")
defaults.synchronize()
self.calcSetting() //Calls another function defined in the same class. That function sends the user a notification.
let notificationName = Notification.Name("GotWebData")
NotificationCenter.default.post(name: notificationName, object: nil)
} // Closes the Dispatch
}
if session.configuration.identifier == "myBGconfig" {
print("about to invalidate the session")
session.invalidateAndCancel()
}
}
を、私は両方のタスクが完了したときに、セッションを殺すためにどのようにまだ考え出したていません今のところinvalidateAndCancelを使って、どちらかが完了したら上のようにkillします。エラーをキャッチする
そして最後に、:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didCompleteWithError: Error?) {
if downloadTask.taskDescription == "rate" {
print("rate download failed with error \(didCompleteWithError)")
}
if downloadTask.taskDescription == "other" {
print("other download failed with error \(didCompleteWithError)")
}
downloadTask.resume() // I'm hoping this retries if a task fails?
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
if let error = error as? NSError {
print("invalidate, error %@/%d", error.domain, error.code)
} else {
print("invalidate, no error")
}
}
@EricD @EricD @EricD @EricD @EricD @EricDあなたがそれをご覧になれば説明を更新しました。 – Raffi
私のコードでURLSessionに問題はありません。ばかげているように思えますが、Xcode 8を使用していますか? :)はいの場合、どこかで矛盾する宣言があるかもしれません。 – Moritz
@EricDはい私は確信しています!私は再び確認し、何が起こるか見る。私が何かを見つけたら更新されます。ありがとう。 – Raffi