How to make NSURLSession POST request in Swift

2019-02-12 03:27发布

问题:

Hi I am very beginner for Swift and I am trying to make NSURLSession "Post" request sending some parameter like my below code

According to my below code response not coming from server can some one help me please

BackGroundClass:-

 import UIKit

protocol sampleProtocal{

    func getResponse(result:NSDictionary)
    func getErrorResponse(error:NSString)
}

class BackGroundClass: NSObject {

    var delegate:sampleProtocal?

    func callPostService(url:String,parameters:NSDictionary){


        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    print("Response: \(json)")
                    self.mainResponse(json)
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                    self.eroorResponse(jsonStr!)
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
                self.eroorResponse(jsonStr!)
            }
        }

        task.resume()
    }

    func mainResponse(result:NSDictionary){
        delegate?.getResponse(result)
    }

    func eroorResponse(result:NSString){
        delegate?.getErrorResponse(result)
    }
}

ViewController:-

import UIKit

class ViewController: UIViewController,sampleProtocal {

    override func viewDidLoad() {
        super.viewDidLoad()

        let delegate = BackGroundClass();
        delegate.self;

        let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>

        let backGround=BackGroundClass();
        backGround.callPostService("url", parameters: params)
    }

    func getResponse(result: NSDictionary) {
        print("Final response is\(result)");
    }

    func getErrorResponse(error: NSString) {
        print("Final Eroor code is\(error)")
    }
}

回答1:

Swift 4 post example-

func postAction(_ sender: Any) {
        let Url = String(format: "your url")
        guard let serviceUrl = URL(string: Url) else { return }
        let parameterDictionary = ["username" : "Test", "password" : "123456"]
        var request = URLRequest(url: serviceUrl)
        request.httpMethod = "POST"
        request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
            return
        }
        request.httpBody = httpBody

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }
            if let data = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    print(json)
                } catch {
                    print(error)
                }
            }
            }.resume()
    }


回答2:

Try to run this function and print the response, it is in Swift 4.0.

Here, I have prepared codable structure:

struct LoginData: Codable {
    var code: Int?
    var message: String?
    var status: String?
    var token: String?
    var data: DataSet?
}
struct DataSet: Codable {
    var email : String?
    var contactNo : String?
    var firstName : String?
    var lastName: String?
    var dob : String?
    var gender : String?
    var address: String?
    var city : String?
    var state : String?
    var country : String?
    var zip : String?
    var username: String?
}

If you get your response printed correctly then pass it to your viewController.

func loginWS(parameters:[String:String], completionHandler: @escaping (Any?) -> Swift.Void) {

    guard let gitUrl = URL(string: BASE_URL+ACTION_URL) else { return }
    print(gitUrl)

    let request = NSMutableURLRequest(url: gitUrl)
    //  uncomment this and add auth token, if your project needs.
    //  let config = URLSessionConfiguration.default
    //  let authString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMywiUGFzc3dvcmQiOiIkMmEkMTAkYVhpVm9wU3JSLjBPYmdMMUk2RU5zdU9LQzlFR0ZqNzEzay5ta1pDcENpMTI3MG1VLzR3SUsiLCJpYXQiOjE1MTczOTc5MjV9.JaSh3FvpAxFxbq8z_aZ_4OhrWO-ytBQNu6A-Fw4pZBY"
    //  config.httpAdditionalHeaders = ["Authorization" : authString]

    let session = URLSession.shared
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])

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

        guard let data = data else { return }
        do {
        //  let decoder = JSONDecoder()
        //  here replace LoginData with your codable structure.
            let gitData = try JSONDecoder().decode(LoginData.self, from: data)
            print("response data:", gitData) 
            completionHandler(gitData)
        } catch let err {
            print("Err", err)
        }
        }.resume()
}


回答3:

Post Class

func post(params : Dictionary<String, String>, url : String) {
    var request = NSMutableURLRequest(URL: NSURL(string: url))
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                var success = parseJSON["success"] as? Int
                println("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
            }
        }
    })

    task.resume()
}

call This Method Like This

 self.post(["username":"jameson", "password":"password"], url: "http://localhost:4567/login")

Hope It Helps :)



回答4:

Http body is missing. Example - setting string paramets as body

let paramString = String(format:"param1=%@&param2=%@",param1,param2)
request.httpBody = paramString.data(using: String.Encoding.utf8)

here just try

request.httpBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)


回答5:

func getData(searchString:String,completion:@escaping(Any)->Void){
    let url = "https://itunes.apple.com/search?term="+searchString
    URLSession.shared.dataTask(with: URL.init(string: url)!){(data,response,err) in
        if let responsedata = data{
            DispatchQueue.main.async {
                completion(responsedata)
            }
        }
    }.resume()
}