8

Apple のおかげで、私の iOS 9 プロジェクト 'Swift 2.3' は、iOS 10 の 'Swift 3' では完全に使用できなくなりました...

の使用に問題があることを除いて、ほとんどすべてを修正しNSURLSessionました。Xcode はURLSession、名前が に変更されたことを通知しています。

宣言されていない型の使用URLSession

ファンデーションは輸入品です。

どうした?!

たとえば、私はこのように使用しています...

lazy var defaultSession: URLSession = {
    let configuration = URLSessionConfiguration.background(withIdentifier: "reCoded.BGDownload")
    configuration.sessionSendsLaunchEvents = true
    configuration.isDiscretionary = true
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue, queue: nil)
    return session
}()

デリゲートメソッドを使用しても同じ問題です。

4

5 に答える 5

7

Foundation.URLSessionどこでも使ってみてくださいURLSession

于 2016-06-20T19:24:26.220 に答える
2

/動作するようになりました/場合によっては、コードを別の場所にコピーしてから、使用するクラス内のすべてを削除してからURLSession、セッションメソッドを再度入力して、コピーしたコードを元に戻してください。

于 2016-06-21T09:36:35.317 に答える
1

URLSessin 関数を次のように更新します。

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    self.data.append(data as Data)  
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if error != nil {
        print("Failed to download data")
    }else {
        print("Data downloaded")
        self.parseJSON()
    }
}
于 2016-12-02T22:24:54.070 に答える
0

方法を説明することはできますが、コードをいじってみると、2 日間のフラストレーションの後、SWIFT 3 で動作するようになりました。SWIFT 3 では、多くの不要な単語が削除されたと思います。

let task = Foundation.URLSession.shared.dataTask(with: <#T##URL#>, completionHandler: <#T##(Data?, URLResponse?, Error?) -> Void#>)
于 2016-10-31T14:15:38.053 に答える
0

ここが今私がいる場所です。完璧ではありませんが、おそらく半分の時間で機能します。

まず、私の 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 を使用して強制終了します。

最後に、エラーをキャッチするには:

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")
    }
}
于 2016-11-11T02:56:53.733 に答える