sendAsynchronousRequest was deprecated in iOS 9, How to alter code to fix

后端 未结 10 2166
长发绾君心
长发绾君心 2020-12-04 15:48

Below is my code I am getting the issue with:

func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
    N         


        
相关标签:
10条回答
  • 2020-12-04 16:22

    Swift implementation

    let session = NSURLSession.sharedSession()
    session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    
    }
    
    0 讨论(0)
  • 2020-12-04 16:22

    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()
    
    0 讨论(0)
  • 2020-12-04 16:22

    Illustrating with an example, the alternative code to the deprecation of:

    sendAsynchronousRequest(_:queue:completionHandler:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]

    Tested and works in Swift 2.1 onwards.

    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()
    
        }
    
    }
    

    //Displays an image on the ViewControllers ImageView. Connect an outlet of the ImageView

    0 讨论(0)
  • 2020-12-04 16:28

    This is the swift 2.1 version:

    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()
    
    0 讨论(0)
提交回复
热议问题