【问题标题】:Make REST API call in Swift在 Swift 中进行 REST API 调用
【发布时间】:2014-08-10 20:25:49
【问题描述】:

我正在尝试使用 Swift 对 REST API 进行 GET 调用,并尝试遵循许多教程,但无法弄清楚。要么是因为我不知道如何将所有 Obj-C 翻译成 Swift,要么是因为有一半的方法 n' 已被弃用。有谁知道如何拨打电话并解析返回的 JSON 数据?

【问题讨论】:

标签: ios swift http rest


【解决方案1】:

非常简单,100% 工作,经过测试

 var url : String = "https://restcountries.eu/rest/v2/all"
       
        URLSession.shared.dataTask(with: NSURL(string: url) as! URL) { data, response, error in
            // Handle result
            
            let response = String (data: data!, encoding: String.Encoding.utf8)
                       print("response is \(response)")

  do {
                        let getResponse = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)

                        print(getResponse)
                        
                        let countryArray = getResponse as! NSArray
                        print(countryArray)
                       
                        let country1 = countryArray[0] as! [String:Any]
                        
                        let name = country1["name"] as! String
                        print(name)
                        
                        
                       } catch {
                           print("error serializing JSON: \(error)")
                       }
        }.resume()
    }

【讨论】:

    【解决方案2】:

    斯威夫特 5

    API调用方式

    //Send Request with ResultType<Success, Error>
        func fetch(requestURL:URL,requestType:String,parameter:[String:AnyObject]?,completion:@escaping (Result<Any>) -> () ){
            //Check internet connection as per your convenience
            //Check URL whitespace validation as per your convenience
            //Show Hud
            var urlRequest = URLRequest.init(url: requestURL)
            urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
            urlRequest.timeoutInterval = 60
            urlRequest.httpMethod = String(describing: requestType)
            urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
            
            //Post URL parameters set as URL body
            if let params = parameter{
                do{
                    let parameterData = try JSONSerialization.data(withJSONObject:params, options:.prettyPrinted)
                    urlRequest.httpBody = parameterData
                }catch{
                   //Hide hude and return error
                    completion(.failure(error))
                }
            }
            //URL Task to get data
            URLSession.shared.dataTask(with: requestURL) { (data, response, error) in
                //Hide Hud
                //fail completion for Error
                if let objError = error{
                    completion(.failure(objError))
                }
                //Validate for blank data and URL response status code
                if let objData = data,let objURLResponse = response as? HTTPURLResponse{
                    //We have data validate for JSON and convert in JSON
                    do{
                        let objResposeJSON = try JSONSerialization.jsonObject(with: objData, options: .mutableContainers)
                        //Check for valid status code 200 else fail with error
                        if objURLResponse.statusCode == 200{
                            completion(.success(objResposeJSON))
                        }
                    }catch{
                        completion(.failure(error))
                    }
                }
            }.resume()
        }
    

    API调用方式的使用

    func useOfAPIRequest(){
            if let baseGETURL = URL(string:"https://postman-echo.com/get?foo1=bar1&foo2=bar2"){
                self.fetch(requestURL: baseGETURL, requestType: "GET", parameter: nil) { (result) in
                          switch result{
                          case .success(let response) :
                            print("Hello World \(response)")
                          case .failure(let error) :
                            print("Hello World \(error)")
                              
                          }
                      }
            }
          
        }
    

    【讨论】:

      【解决方案3】:
      func getAPICalling(mainUrl:String) {
          //create URL
          guard let url = URL(string: mainUrl) else {
            print("Error: cannot create URL")
            return
          }
          //create request
          let urlRequest = URLRequest(url: url)
          
          // create the session
          let config = URLSessionConfiguration.default
          let session = URLSession(configuration: config)
          
          // make the request
          let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
              
            // check for any errors
            guard error == nil else {
              print("error calling GET")
              print(error!.localizedDescription)
              return
            }
              
            // make sure we got data
            guard let responseData = data else {
              print("error: did not receive data")
              return
            }
              
            // convert Data in JSON && parse the result as JSON, since that's what the API provides
            do {
              guard let object = try JSONSerialization.jsonObject(with: responseData, options: [])
                as? [String: Any] else {
                  print("error trying to convert data to JSON")
                  return
              }
              //JSON Response
              guard let todoTitle = object["response"] as? NSDictionary else {
                print("Could not get todo title from JSON")
                return
              }
              
              //Get array in response
              let responseList = todoTitle.value(forKey: "radioList") as! NSArray
              
              for item in responseList {
                  let dic = item as! NSDictionary
                  let str = dic.value(forKey: "radio_des") as! String
                  self.arrName.append(str)
                  print(item)
              }
              
              DispatchQueue.main.async {
                  self.tblView.reloadData()
              }
              
            } catch  {
              print("error trying to convert data to JSON")
              return
            }
          }
          task.resume()
      }
      

      用法:

      getAPICalling(mainUrl:"https://dousic.com/api/radiolist?user_id=16")

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          在 swift 3.3 和 4 中。我用两个公共方法创建了 APIManager 类。只需传递所需的参数、api 名称和请求类型。您将得到响应,然后将其传递给闭包。

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

          【讨论】:

            【解决方案6】:
            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()
                        }
            

            【讨论】:

              【解决方案7】:

              使用模型类的 API 调用

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

              创建变量并连接模型类

              var modelReference = [model]()
              

              创建一个模型类 New -> swift 类

              import Foundation
              class model : NSObject{
              var name : String
              var descriptionStr: String
              
              init(name : String, descriptionStr: String)
              {
                  self.name = name
                  self.descriptionStr = descriptionStr
              }
              

              }

              然后我们可以连接我们的表视图对象

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

              【讨论】:

                【解决方案8】:

                Swift 4 - GET 请求

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

                如果您在不使用 HTTPS 的情况下访问端点,请不要忘记配置应用程序传输安全设置以将您的域添加到例外中并允许不安全的 http 请求。

                您可以使用http://www.json4swift.com/ 之类的工具从您的 JSON 响应中自动生成可编码映射。

                【讨论】:

                • 什么是CustomDtoClass??
                • @BijenderSinghShekhawat 这是一个用于反序列化的具有可编码映射的类。我发布的那个 json4swift 链接可以从输入的 JSON 数据中为您生成这些链接。它基本上只是创建一个类来表示您的数据传输对象。
                【解决方案9】:

                斯威夫特 4

                使用 Alamofire 和 Api Post 方法创建应用

                为带有 Xcode 9 的 Swift 3 安装 pod 文件 -pod 'Alamofire', '~> 4.0'

                创建 Webservices.swift 类,导入 Alamofire

                设计故事板,登录查看

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

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

                【讨论】:

                  【解决方案10】:

                  斯威夫特 4

                  在我们的 App 中使用 ALAMOFIRE,请安装 pod 文件

                  pod 'Alamofire', '~> 4.0'

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

                  然后我们可以为我们的项目-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)
                          }
                  }
                  }
                  

                  然后创建 NetworkingError.swift 类

                  import Foundation
                  enum networkingError : Error{
                      case badNetworkigStuff
                  
                  }
                  

                  然后创建 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)
                          }
                      }
                  }
                  

                  然后创建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
                          }
                      }
                  }
                  

                  然后创建 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
                          }
                  }
                  

                  然后是我们的视图控制器类

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

                  在我们的故事板中

                  请使用带有标识符 -peopleToDetails 的 segue 将我们的视图与另一个视图连接起来

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

                  • 使用 UIButton 获取数据

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

                  【讨论】:

                    【解决方案11】:

                    你可以这样做:

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

                    编辑:对于对此有疑问的人,也许您的 JSON 流是 数组 [] 而不是对象 {} 因此您必须将 jsonResult 更改为 NSArray 而不是 NSDictionary

                    【讨论】:

                    • 实际上在 Swift 中使用带有闭包的异步方法要好得多,因为语言本身就是为此而设计的。
                    • 当我尝试上述方法时,由于方法名称重复,即使它们接受不同的参数,我也会收到编译器错误。我还可以获得一个解析字典中 JSON 的小例子吗?我翻译时发现的所有 Obj-C 材料都不起作用。
                    • 由于某种原因,当我进行 api 调用时,我收到 0x0000000000000000 错误。我不知道如何绕过它。谁能指出我正确的方向?
                    • @TiffanyLowe 发现错误!如果其他人需要一个可行的解决方案:如果您的 JSON 响应以数组的形式出现,那么 jsonResult 应该被“转换”为 NSArray 而不是 NSDictionary。
                    • NSURLConnection.sendAsynchronousRequest 实际上已从 iOS 9 和 macOS 10.11 弃用。正确答案是关于 NSUrlSession.dataTaskWithUrl() 的答案。
                    【解决方案12】:

                    斯威夫特 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()
                    

                    【讨论】:

                      【解决方案13】:

                      如果您使用 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()
                      

                      【讨论】:

                        【解决方案14】:

                        这里是在 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()
                        

                        我希望它有效。

                        【讨论】:

                          【解决方案15】:

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

                          【讨论】:

                            【解决方案16】:

                            我认为NSURLSession api 更适合这种情况。因为如果您编写 swift 代码,您的项目目标至少是 iOS 7 并且 iOS 7 支持NSURLSession api。反正这里是代码

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

                            【讨论】:

                            • @mustafa 是否可以在此调用中指定 HTTP 请求类型,如“GET”、“POST”?在这种情况下,我如何将值传递给调用的标题或正文?
                            • 有dataTaskWithRequest方法。你可以传递给它 NSURLRequest 或 NSMutableURLRequest 实例。
                            • // Handle result 可能是:let resp = String( data:data!, encoding:NSUTF8StringEncoding)!
                            • 比使用NSURLSessionConfiguration 简单得多。我认为这应该是公认的答案。
                            猜你喜欢
                            • 2017-07-10
                            • 2016-06-07
                            • 1970-01-01
                            • 2015-01-27
                            • 2015-03-19
                            • 1970-01-01
                            • 1970-01-01
                            • 2019-06-11
                            • 2021-06-29
                            相关资源
                            最近更新 更多