Make REST API call in Swift

前端 未结 15 1358
被撕碎了的回忆
被撕碎了的回忆 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: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
    
        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.

提交回复
热议问题