web-dev-qa-db-ja.com

sendAsynchronousRequestはiOS 9で廃止されました。修正するコードの変更方法

以下は私が問題を抱えている私のコードです:

func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in

        if ((error) != nil)
        {
            callback(feed: nil, error: error)
        }
        else
        {
            self.callbackClosure = callback

            let parser : NSXMLParser = NSXMLParser(data: data!)
            parser.delegate = self
            parser.shouldResolveExternalEntities = false
            parser.parse()
        }
    }
}

これは現在iOS 9で非推奨になり、代わりにdataTaskWithRequestを使用するように指示されています。誰かがdataTaskでsendAsyncを変更するのを手伝ってもらえますか?.

47
Dom Bryan

以下のように代わりにNSURLSessionを使用してください。

Objective-Cの場合

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] resume];

Swiftの場合、

    var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var params = ["username":"username", "password":"password"] as Dictionary<String, String>

    request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")})

    task.resume()

非同期クエリの場合、from Apple docs

ほとんどのネットワークAPIと同様に、NSURLSession APIは非常に非同期です。呼び出すメソッドに応じて、2つの方法のいずれかでデータを返します。

転送が正常に終了したとき、またはエラーが発生したときにアプリにデータを返す完了ハンドラーブロックへ。

データが受信されると、カスタムデリゲートでメソッドを呼び出します。

ファイルへのダウンロードが完了したときにカスタムデリゲートのメソッドを呼び出すことにより。

75
Nilesh Patel

迅速な実装

let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in

}
16
Ankit Sachan

Swift 3.0

var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
let session = URLSession.shared

session.dataTask(with: request) {data, response, err in
    print("Entered the completionHandler")
}.resume()
10
karma

これはSwift 2.1バージョンです:

let request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

let params = ["username":"username", "password":"password"] as Dictionary<String, String>

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})

task.resume()
9
user4243768

Swift 2.0:

古い(以下の「新規」に置き換え):

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response, data, error) -> Void in

// Code

}

新着:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in

// Code

}
task.resume()
4
Elliott Davies

Swift 4

let params = ["email":"[email protected]", "password":"123456"] as Dictionary<String, String>

var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in

    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
        print(json)
    } catch {
        print("error")
    }

})

task.resume()
1
Haroldo Gondim

with Swift 3.1

let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL)
    let session = URLSession.shared
    request.httpMethod = "POST"

    let params = ["username":"username", "password":"password"] as Dictionary<String, String>

    request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Response: \(String(describing: response))")})

    task.resume()
1
Imtee

これは、Swift3.0バージョンの Nilesh Patel's Answer JSONSerialisedデータです

let url = URL(string: "<HERE GOES SERVER API>")!
            var request = URLRequest(url: url)
            request.httpMethod = "POST" //GET OR DELETE etc....
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("<ValueforAuthorization>", forHTTPHeaderField: "Authorization")
            let parameter = [String:Any]() //This is your parameters [String:Any]
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: parameter, options: .prettyPrinted)
                // here "jsonData" is the dictionary encoded in JSON data
                request.httpBody = jsonData
                let session = URLSession(configuration: .default)
                let task = session.dataTask(with: request, completionHandler: { (incomingData, response, error) in
                    if let error = error {
                        print(error.localizedDescription)
                        print(request)
                    }else if let response = response {
                        print(response)
                    }else if let incomingData = incomingData {
                        print(incomingData)
                    }
                })
                task.resume()

            } catch {
                print(error.localizedDescription)
            }
0
Vatsal Shukla

Swift 4.2

これは私のために働いた:

func loadImageFromURL(URL: NSURL) {
    let request = URLRequest(url: URL as URL)
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let imageData = data {
            DispatchQueue.main.async {
                self.imageView.image = UIImage(data: imageData)
            }
        }
    }
    task.resume()
}

メインスレッドのみがUI要素を変更することになっているため、ランタイム警告があったため、「DispatchQueue.main.async {}」を追加する必要がありました。

0

廃止予定の代替コードを例に示します:

sendAsynchronousRequest(_:queue:completionHandler :) 'はiOS 9.0で非推奨になりました:[NSURLSession dataTaskWithRequest:completionHandler:]を使用します

Swift 2.1以降でテストおよび動作します。

import UIKit

class ViewController: UIViewController {


    @IBOutlet var theImage: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()


        let url = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg")


        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in

            if error != nil {
                print("thers an error in the log")
            } else {

                dispatch_async(dispatch_get_main_queue()) {
                let image = UIImage(data: data!)
                self.theImage.image = image

                }
            }

        }

        task.resume()

    }

}

// ViewControllers ImageViewに画像を表示します。 ImageViewのコンセントを接続します

0
Naishta