Swift 3 - 使用API​​调用的最新方法

时间:2017-07-27 03:54:19

标签: ios api swift3

使用swift 3在iOS应用中管理API调用的最新和最新方法是什么?

是NSURLSession吗?或者还有另一种方法可以做到更新吗?

3 个答案:

答案 0 :(得分:2)

在swift 3 NS前缀被删除,现在以下是urlsession的语法

URLSession.shared.dataTask(with: url!) { (data, response, error) in
         //do the work
}

答案 1 :(得分:2)

在swift 3中 - api的最新方法调用。

let url = URL(string: urlString)! //Pass the URL String format
var request = URLRequest(url: url)

_ = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
                    print(error?.localizedDescription ?? "No data")
                        self.ProgressViewHide()
                        return
                    }
     DispatchQueue.main.async {
          let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
                // Get Response on responseJSON
     }

}.resume()

答案 2 :(得分:1)

因此,对于Swift 3.x中的新方法,你必须这样做。

另外,请记住你的闭包是异步工作的,所以我使用GCD将调用包装在主线程上执行。

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Chrome with ng serve",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:4200",
      "webRoot": "${workspaceRoot}"
    },
    {
      "name": "Launch Chrome with ng test",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:9876/debug.html",
      "webRoot": "${workspaceRoot}"
    },
    {
      "name": "Launch ng e2e",
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/protractor/bin/protractor",
      "protocol": "inspector",
      "args": ["${workspaceRoot}/protractor.conf.js"]
    }      
  ]
}

但是,我建议您使用更简单的方法来处理使用Alamofire的网络, https://github.com/Alamofire/Alamofire