Make REST API call in Swift

前端 未结 15 1319
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

相关标签:
15条回答
  • 2020-12-02 04:43

    Swift 5

    API call method

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

    Use of API call method

    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)")
                              
                          }
                      }
            }
          
        }
    
    0 讨论(0)
  • 2020-12-02 04:44

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

    In swift 3.3 and 4. I crated APIManager class with two public methods. Just pass required parameter, api name and request type. You will get response then pass it to the closure.

     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()
      }
    
    0 讨论(0)
  • 2020-12-02 04:48

    Here is the complete code for REST API requests using 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()
    

    For POST request ...

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

    I hope it works.

    0 讨论(0)
  • 2020-12-02 04:50

    Swift 4

    Create an app using Alamofire with Api Post method

    Install pod file -pod 'Alamofire', '~> 4.0' for Swift 3 with Xcode 9

    Create Webservices.swift class, import Alamofire

    Design storyBoard ,Login View

    insert following Code for the 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)
        }
    
    }
    

    Insert Following Code For 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() }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 04:52

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

    Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.

    You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.

    0 讨论(0)
提交回复
热议问题