Effettua una chiamata API REST in Swift


92

Sto cercando di utilizzare Swift per effettuare una chiamata GET a un'API REST e ho provato a seguire numerosi tutorial, ma non riesco a capirlo. O perché non riesco a capire come tradurre tutto l'Obj-C in Swift, o perché metà dei metodi n 'tali sono deprecati. Qualcuno sa come effettuare la chiamata e analizzare i dati JSON restituiti?


Non riesco a trovare gli altri che ho trovato, ma ho provato a installare RESTkit ma era troppo complicato e non è stato tradotto in Xcode 6 da Xcode 4. Ho anche provato blog.strikeiron.com/bid/63338/…
cclloyd


2
Ti consiglierei di provare Alamofire . È una libreria esterna che semplifica le richieste HTTP e la gestione delle risposte (IMO).
Alvaro

Un semplice esempio può essere trovato in questa risposta .
david72

Risposte:


65

Puoi fare così:

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
    }


})

EDIT: Per le persone che hanno problemi con questo, forse il tuo flusso JSON è un array [] e non un oggetto {}, quindi devi cambiare jsonResult in NSArrayinvece diNSDictionary


6
In realtà è molto meglio usare metodi asincroni con chiusura in Swift poiché il linguaggio stesso è progettato per questo.
Francescu

Quando provo quanto sopra, ottengo un errore del compilatore a causa dei nomi dei metodi duplicati, anche se accettano parametri diversi. Inoltre posso ottenere un piccolo esempio di analisi del JSON nel dizionario? Nessuna delle cose Obj-C che ho trovato ha funzionato quando l'ho tradotta.
cclloyd

2
Per qualche motivo quando effettuo una chiamata API ricevo un errore 0x0000000000000000. Non so come aggirarlo. Qualcuno può indicarmi la giusta direzione?
Tiffany Lowe

2
@TiffanyLowe Trovato l'errore! Se qualcun altro ha bisogno di una soluzione possibile: se la tua risposta JSON si presenta sotto forma di un array, jsonResult dovrebbe essere "castato" come NSArray non come NSDictionary.
romsearcher

1
NSURLConnection.sendAsynchronousRequest è attualmente deprecato da iOS 9 e macOS 10.11. Le risposte corrette sono quelle riguardanti NSUrlSession.dataTaskWithUrl ().
Yusef Maali

56

Swift 5 e 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()

25

Penso che l' NSURLSessionAPI si adatti meglio a questa situazione. Perché se scrivi codice swift, l'obiettivo del tuo progetto è almeno iOS 7 e iOS 7 supporta NSURLSessionapi. Comunque ecco il codice

let url = "YOUR_URL"

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

1
@mustafa è possibile specificare il tipo di richiesta HTTP come "GET", "POST" in questa chiamata? anche come posso passare valore all'intestazione o al corpo della chiamata in questo caso?
Rezoan

C'è il metodo dataTaskWithRequest. Puoi passare l'istanza NSURLRequest o NSMutableURLRequest.
mustafa

// Handle resultpotrebbe essere:let resp = String( data:data!, encoding:NSUTF8StringEncoding)!
Jose Manuel Abarca Rodríguez

Molto più semplice dell'utilizzo NSURLSessionConfiguration. Penso che questa dovrebbe essere la risposta accettata.
kakubei

20

Ecco il codice completo per le richieste API REST utilizzando NSURLSession in swift

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

Per richiesta 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()

Spero che funzioni.


10

modificato per swift 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()

8

Swift 4 - GET request

var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"

URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
    do {
        let jsonDecoder = JSONDecoder()
        let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
        print(responseModel)
    } catch {
        print("JSON Serialization error")
    }
}).resume()

Non dimenticare di configurare le impostazioni di sicurezza del trasporto app per aggiungere il tuo dominio alle eccezioni e consentire richieste http non sicure se stai raggiungendo gli endpoint senza utilizzare HTTPS.

Puoi utilizzare uno strumento come http://www.json4swift.com/ per generare automaticamente le tue mappature codificabili dalle tue risposte JSON.


1
cos'è CustomDtoClass ??
Bijender Singh Shekhawat

@BijenderSinghShekhawat che è una classe con mappature codificabili da utilizzare per la deserializzazione. Quel collegamento json4swift che ho pubblicato può generarli per te da un input di dati JSON. Fondamentalmente si tratta solo di creare una classe per rappresentare il tuo oggetto di trasferimento dati.
Jyosua

5

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

5

Swift 4

Crea un'app utilizzando Alamofire con il metodo Api Post

Installa il file pod -pod 'Alamofire', '~> 4.0' per Swift 3 con Xcode 9

Crea la classe Webservices.swift, importa Alamofire

Design storyBoard, Visualizzazione accesso

inserire il seguente codice per ViewControllerClass

import UIKit

class ViewController: UIViewController {

    @IBOutlet var usernameTextField: UITextField!

    @IBOutlet var passwordTextField: UITextField!
    var usertypeStr :String = "-----------"
    var loginDictionary : NSDictionary?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loginButtonClicked(_ sender: Any) {
        WebServices.userLogin(userName: usernameTextField.text!, password: passwordTextField.text!,userType: usertypeStr) {(result, message, status )in
            if status {
                let loginDetails = result as? WebServices
                self.loginDictionary = loginDetails?.loginData
                if self.loginDictionary?["status"] as? String == "error"
                {
                    self.alertMessage(alerttitle: "Login Error", (self.loginDictionary?["message"] as? String)!)
                } else if self.loginDictionary?["status"] as? String == "ok" {
                    self.alertMessage(alerttitle: "", "Success")

                }else {
                    self.alertMessage(alerttitle: "", (self.loginDictionary?["message"] as? String)!)
                }
            } else {
                self.alertMessage(alerttitle: "", "Sorry")
            }
        }
    }

    func alertMessage(alerttitle:String,_ message : String){
        let alertViewController = UIAlertController(title:alerttitle,  message:message, preferredStyle: .alert)
        alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alertViewController, animated: true, completion: nil)
    }

}

Inserisci il seguente codice per WebserviceClass

import Foundation
import Alamofire
class WebServices: NSObject {
    enum WebServiceNames: String {
        case baseUrl = "https://---------------"
        case UserLogin = "------------"
    }

    // MARK: - Login Variables
    var loginData : NSDictionary?

    class func userLogin(userName: String,password : String,userType : String, completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> ()) {
        let url = WebServiceNames.baseUrl.rawValue + WebServiceNames.UserLogin.rawValue
        let params = ["USER": userName,"PASS":password,"API_Key" : userType]
        WebServices.postWebService(urlString: url, params: params as [String : AnyObject]) { (response, message, status) in
            print(response ?? "Error")
            let result = WebServices()
            if let data = response as? NSDictionary {
                print(data)
                result.loginData = data
                completion(result, "Success", true)

            }else {
                completion("" as AnyObject?, "Failed", false)
            }
        }
    }
    //MARK :- Post
    class func postWebService(urlString: String, params: [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void) {
        alamofireFunction(urlString: urlString, method: .post, paramters: params) { (response, message, success) in
            if response != nil {
                completion(response as AnyObject?, "", true)
            }else{
                completion(nil, "", false)
            }
        }
    }

    class func alamofireFunction(urlString : String, method : Alamofire.HTTPMethod, paramters : [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void){

        if method == Alamofire.HTTPMethod.post {
            Alamofire.request(urlString, method: .post, parameters: paramters, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

                print(urlString)

                if response.result.isSuccess{
                    completion(response.result.value as AnyObject?, "", true)
                }else{
                    completion(nil, "", false)
                }
            }

        }else {
            Alamofire.request(urlString).responseJSON { (response) in

                if response.result.isSuccess{
                    completion(response.result.value as AnyObject?, "", true)
                }else{
                    completion(nil, "", false)
                }
            }
        }
    }



    //Mark:-Cancel
    class func cancelAllRequests()
    {
        Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
            dataTasks.forEach { $0.cancel() }
            uploadTasks.forEach { $0.cancel() }
            downloadTasks.forEach { $0.cancel() }
        }
    }
}

4

In swift 3.3 e 4. Ho creato la classe APIManager con due metodi pubblici. Basta passare il parametro richiesto, il nome api e il tipo di richiesta. Riceverai una risposta quindi passala alla chiusura.

 import UIKit   

    struct RequestType {
      static let  POST = "POST"
      static let  GET = "GET"
    }

    enum HtttpType: String {
      case POST = "POST"
      case GET  = "GET"
    }

    class APIManager: NSObject {


      static let sharedInstance: APIManager = {

        let instance = APIManager()
        return instance
      }()
     private init() {}
        // First Method

          public func requestApiWithDictParam(dictParam: Dictionary<String,Any>, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void) {

            var apiUrl = “” // Your api url
            apiUrl =  apiUrl.appendingFormat("%@", apiName)
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
            let url = URL(string: apiUrl)!
            let HTTPHeaderField_ContentType  = "Content-Type"
            let ContentType_ApplicationJson  = "application/json"
            var request = URLRequest.init(url: url)

            request.timeoutInterval = 60.0
            request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
            request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
            request.httpMethod = requestType

            print(apiUrl)
            print(dictParam)

            let dataTask = session.dataTask(with: request) { (data, response, error) in

              if error != nil   {
                completionHendler(nil, error as NSError?, false)
              } do {
                let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                print("Request API = ", apiUrl)
                print("API Response = ",resultJson ?? "")
                completionHendler(resultJson, nil, true)

              } catch {
                completionHendler(nil, error as NSError?, false)
              }
            }
            dataTask.resume()
          }

           // Second Method
           public func requestApiWithUrlString(param: String, apiName: String,requestType: String, isAddCookie: Bool, completionHendler:@escaping (_ response:Dictionary<String,AnyObject>?, _ error: NSError?, _ success: Bool)-> Void ) {
                var apiUrl = "" // Your api url
                let config = URLSessionConfiguration.default
                let session = URLSession(configuration: config)            
                var request: URLRequest?

                if requestType == "GET" {

                  apiUrl =  String(format: "%@%@&%@", YourAppBaseUrl,apiName,param)
                  apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                  print("URL=",apiUrl)

                  let url = URL(string: apiUrl)!
                  request = URLRequest.init(url: url)
                  request?.httpMethod = "GET"

                } else {

                  apiUrl =  String(format: "%@%@", YourAppBaseUrl,apiName)
                  apiUrl = apiUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                  print("URL=",apiUrl)

                  let bodyParameterData = param.data(using: .utf8)
                  let url = URL(string: apiUrl)!

                  request = URLRequest(url: url)
                  request?.httpBody = bodyParameterData
                  request?.httpMethod = "POST"
                }

                request?.timeoutInterval = 60.0
                request?.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
                request?.httpShouldHandleCookies = true

                let dataTask = session.dataTask(with: request!) { (data, response, error) in

                  if error != nil {
                    completionHendler(nil, error as NSError?, false)
                  } do {
                    if data != nil  {
                      let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

                      print("Request API = ", apiUrl)
                      print("API Response = ",resultJson ?? "")
                      completionHendler(resultJson, nil, true) 
                    } else  {
                      completionHendler(nil, error as NSError?, false)
                    }
                  } catch {
                    completionHendler(nil, error as NSError?, false)
                  }
                }
                dataTask.resume()
              }
    }

    // Here is example of calling Post API from any class

     let bodyParameters = String(format: "appid=%@&appversion=%@","1","1")
            APIManager.sharedInstance.requestApiWithUrlString(param: bodyParameters, apiName: "PASS_API_NAME", requestType: HtttpType.POST.rawValue, isAddCookie: false) { (dictResponse, error, success) in

                if success {
                    if let dictMessage = dictResponse?["message"] as? Dictionary<String, AnyObject> {
                // do you work
                    }

                }  else {
                    print("Something went wrong...")
                }
            }
        }


/// Or just use simple function 

func dataRequest() {
    let urlToRequest = "" // Your API url

    let url = URL(string: urlToRequest)!
    let session4 = URLSession.shared
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    let paramString = "data=Hello"
    request.httpBody = paramString.data(using: String.Encoding.utf8)
    let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
      guard let _: Data = data, let _: URLResponse = response, error == nil else {
        print("*****error")
        return
      }
      if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
          print("****Data: \(dataString)") //JSONSerialization
      }
    }
    task.resume()
  }

3

rapido 4

USA ALAMOFIRE nel nostro file pod di installazione App plz

pod "Alamofire", "~> 4.0"

Possiamo usare l'API per i dati Json - https://swapi.co/api/people/

Quindi possiamo creare una classe di networking per il nostro progetto: networkingService.swift

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

Quindi crea la classe NetworkingError.swift

import Foundation
enum networkingError : Error{
    case badNetworkigStuff

}

Quindi crea la classe Person.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)
        }
    }
}

Quindi crea DetailVC.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
        }
    }
}

Quindi crea la classe GetPeopleResponse.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
        }
}

Quindi la nostra classe controller di visualizzazione

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

Nel nostro StoryBoard

plz Connettiti con la nostra vista con un'altra usando segue con identificatore -peopleToDetails

  • Usa UITableView nella nostra prima vista

  • Usa UIButton per ottenere i dati

  • Usa 9 etichette nel nostro DetailVc


2

Se stai lavorando in Swift 3, la sintassi cambia. L'esempio qui ha funzionato per me e ha una buona spiegazione dei passaggi: https://grokswift.com/simple-rest-with-swift/

Questo è il codice di quel tutorial:

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

0

Chiamata API utilizzando la classe del modello

    let urlString = "http://--.154.--.78/------/index.php?route=api/coupon/all"

    let url = URL(string: urlString)
    var request = URLRequest(url: url!)
    request.httpMethod = "GET"

    URLSession.shared.dataTask(with:request) { (data, response, error) in
        if error != nil {
            print(error)
        } else {
            do {

                let parsedDictionaryArray = try JSONSerialization.jsonObject(with: data!) as! [String:AnyObject]
                print(parsedDictionaryArray)

                if let arry = parsedDictionaryArray["data"] as? [[String:AnyObject]] {
                for dic in arry {
                    let name = dic["name"]
                    let descriptionData = dic["description"]
                    self.modelReference.append(model(name: name as! String, descriptionStr: descriptionData as! String))
                    print(name!)
                }
                }
            } catch let error as NSError {
                print(error)
            }
        }

        }.resume()

creare una variabile e connettersi con la classe del modello

var modelReference = [model]()

creare una classe modello Nuovo -> classe rapida

import Foundation
class model : NSObject{
var name : String
var descriptionStr: String

init(name : String, descriptionStr: String)
{
    self.name = name
    self.descriptionStr = descriptionStr
}

}

quindi possiamo connetterci con i nostri oggetti di visualizzazione tabella

let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID")as! TableViewCell
    cell.listName.text = modelReference[indexPath.row].name

0
let headers = [
                "cache-control": "no-cache",
                "postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
            ]

            let request = NSMutableURLRequest(url: NSURL(string: "Your url string")! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "GET"
            request.allHTTPHeaderFields = headers

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if error == nil && data != nil {
                    do {
                        // Convert NSData to Dictionary where keys are of type String, and values are of any type
                        let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                        print(json)

                        //do your stuff

                      //  completionHandler(true)

                    } catch {
                       // completionHandler(false)
                    }
                }
                else if error != nil
                {
                    //completionHandler(false)
                }
            }).resume()
            }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.