在Swift中进行REST API调用

我正在尝试使用Swift对REST API进行GET调用,并试图遵循大量的教程,但无法弄清楚。 要么是因为我不知道如何将所有的Obj-C转换成Swift,或者是因为某些方法的一半已经被弃用了。 有谁知道如何进行调用,并parsing返回的JSON数据?

你可以这样做:

var url : String = "http://google.com?test=toto&test2=titi" var request : NSMutableURLRequest = NSMutableURLRequest() request.URL = NSURL(string: url) request.HTTPMethod = "GET" NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary if (jsonResult != nil) { // process jsonResult } else { // couldn't load JSON, look at error } }) 

编辑:人们有这个问题也许你的JSONstream是一个数组[]而不是一个对象{}所以你必须改变NSArray而不是NSDictionary jsonResult

我认为NSURLSession API在这种情况下更好。 因为如果你编写swift代码,你的项目目标至less是iOS 7,iOS 7支持NSURLSession api。 无论如何,这里的代码

 let url = "YOUR_URL" NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)) { data, response, error in // Handle result }.resume() 

以下是在swift中使用NSURLSession的REST API请求的完整代码

 For GET Request let configuration = NSURLSessionConfiguration .defaultSessionConfiguration() let session = NSURLSession(configuration: configuration) let urlString = NSString(format: "your URL here") print("get wallet balance url string is \(urlString)") //let url = NSURL(string: urlString as String) let request : NSMutableURLRequest = NSMutableURLRequest() request.URL = NSURL(string: NSString(format: "%@", urlString) as String) request.HTTPMethod = "GET" request.timeoutInterval = 30 request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let dataTask = session.dataTaskWithRequest(request) { (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in // 1: Check HTTP Response for successful GET request guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data else { print("error: not a valid http response") return } switch (httpResponse.statusCode) { case 200: let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding) print("response is \(response)") do { let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments) EZLoadingActivity .hide() // } } catch { print("error serializing JSON: \(error)") } break case 400: break default: print("wallet GET request got response \(httpResponse.statusCode)") } } dataTask.resume() 

对于POST请求…

 let configuration = NSURLSessionConfiguration .defaultSessionConfiguration() let session = NSURLSession(configuration: configuration) let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject> let urlString = NSString(format: “your URL”); print("url string is \(urlString)") let request : NSMutableURLRequest = NSMutableURLRequest() request.URL = NSURL(string: NSString(format: "%@", urlString)as String) request.HTTPMethod = "POST" request.timeoutInterval = 30 request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: []) let dataTask = session.dataTaskWithRequest(request) { (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in // 1: Check HTTP Response for successful GET request guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data else { print("error: not a valid http response") return } switch (httpResponse.statusCode) { case 200: let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding) if response == "SUCCESS" { } default: print("save profile POST request got response \(httpResponse.statusCode)") } } dataTask.resume() 

我希望它的作品。

编辑为迅速2

 let url = NSURL(string: "http://www.test.com") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in print(NSString(data: data!, encoding: NSUTF8StringEncoding)) } task.resume() 

如果你在Swift 3中工作,语法会改变。 这里的例子为我工作,并有一个很好的步骤说明: https : //grokswift.com/simple-rest-with-swift/

这是该教程的代码:

 let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1" guard let url = URL(string: todoEndpoint) else { print("Error: cannot create URL") return } let urlRequest = URLRequest(url: url) let task = session.dataTask(with: urlRequest) { (data, response, error) in // check for any errors guard error == nil else { print("error calling GET on /todos/1") print(error!) return } // make sure we got data guard let responseData = data else { print("Error: did not receive data") return } // parse the result as JSON, since that's what the API provides do { guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else { print("error trying to convert data to JSON") return } // now we have the todo // let's just print it to prove we can access it print("The todo is: " + todo.description) // the todo object is a dictionary // so we just access the title using the "title" key // so check for a title and print it if we have one guard let todoTitle = todo["title"] as? String else { print("Could not get todo title from JSON") return } print("The title is: " + todoTitle) } catch { print("error trying to convert data to JSON") return } } task.resume() 

斯威夫特4

 let params = ["username":"john", "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 print(response!) do { let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject> print(json) } catch { print("error") } }) task.resume() 

Swift 3.0

 let request = NSMutableURLRequest(url: NSURL(string: "http://httpstat.us/200")! as URL) let session = URLSession.shared request.httpMethod = "GET" 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 if error != nil { print("Error: \(String(describing: error))") } else { print("Response: \(String(describing: response))") } }) task.resume() 

迅速4

在我们的应用程序中使用ALAMOFIRE安装pod文件

荚'Alamofire','〜> 4.0'

我们可以使用Json数据API – https://swapi.co/api/people/

然后我们可以为我们的项目networkingService.swift创build一个networking类

 import Foundation import Alamofire typealias JSON = [String:Any] class networkingService{ static let shared = networkingService() private init() {} func getPeople(success successblock: @escaping (GetPeopleResponse) -> Void) { Alamofire.request("https://swapi.co/api/people/").responseJSON { response in guard let json = response.result.value as? JSON else {return} // print(json) do { let getPeopleResponse = try GetPeopleResponse(json: json) successblock(getPeopleResponse) }catch{} } } func getHomeWorld(homeWorldLink:String,completion: @escaping(String) ->Void){ Alamofire.request(homeWorldLink).responseJSON {(response) in guard let json = response.result.value as? JSON, let name = json["name"] as? String else{return} completion(name) } } } 

然后创buildNetworkingError.swift类

 import Foundation enum networkingError : Error{ case badNetworkigStuff } 

然后创buildPerson.swift类

 import Foundation struct Person { private let homeWorldLink : String let birthyear : String let gender : String let haircolor : String let eyecolor : String let height : String let mass : String let name : String let skincolor : String init?(json : JSON) { guard let birthyear = json["birth_year"] as? String, let eyecolor = json["eye_color"] as? String, let gender = json["gender"] as? String, let haircolor = json["hair_color"] as? String, let height = json["height"] as? String, let homeWorldLink = json["homeworld"] as? String, let mass = json["mass"] as? String, let name = json["name"] as? String, let skincolor = json["skin_color"] as? String else { return nil } self.homeWorldLink = homeWorldLink self.birthyear = birthyear self.gender = gender self.haircolor = haircolor self.eyecolor = eyecolor self.height = height self.mass = mass self.name = name self.skincolor = skincolor } func homeWorld(_ completion: @escaping (String) -> Void) { networkingService.shared.getHomeWorld(homeWorldLink: homeWorldLink){ (homeWorld) in completion(homeWorld) } } } 

然后创buildDetailVC.swift

 import UIKit class DetailVC: UIViewController { var person :Person! @IBOutlet var name: UILabel! @IBOutlet var birthyear: UILabel! @IBOutlet var homeworld: UILabel! @IBOutlet var eyeColor: UILabel! @IBOutlet var skinColor: UILabel! @IBOutlet var gender: UILabel! @IBOutlet var hairColor: UILabel! @IBOutlet var mass: UILabel! @IBOutlet var height: UILabel! override func viewDidLoad() { super.viewDidLoad() print(person) name.text = person.name birthyear.text = person.birthyear eyeColor.text = person.eyecolor gender.text = person.gender hairColor.text = person.haircolor mass.text = person.mass height.text = person.height skinColor.text = person.skincolor person.homeWorld{(homeWorld) in self.homeworld.text = homeWorld } } } 

然后创buildGetPeopleResponse.swift类

 import Foundation struct GetPeopleResponse { let people : [Person] init(json :JSON) throws { guard let results = json["results"] as? [JSON] else { throw networkingError.badNetworkigStuff} let people = results.map{Person(json: $0)}.flatMap{ $0 } self.people = people } } 

然后我们的视图控制器类

 import UIKit class ViewController: UIViewController { @IBOutlet var tableVieww: UITableView! var people = [Person]() @IBAction func getAction(_ sender: Any) { print("GET") networkingService.shared.getPeople{ response in self.people = response.people self.tableVieww.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "peopleToDetails", let detailVC = segue.destination as? DetailVC, let person = sender as AnyObject as? Person else {return} detailVC.person = person } } extension ViewController:UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = people[indexPath.row].name return cell } } extension ViewController:UITableViewDelegate{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "peopleToDetails", sender: people[indexPath.row]) } } 

在我们的故事板

plz连接我们的视图与另一个使用segue与标识符-peopleToDetails

  • 在我们的第一个视图中使用UITableView

  • 使用UIButton获取数据

  • 在我们的DetailVc中使用9个标签