Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define Content-type in Swift using NSURLSession

Tags:

I want to set content-type in my below code to call web api. Content-type will be application/json; charset=utf-8

let url = NSURL(string: "http:/api/jobmanagement/PlusContactAuthentication?email=\(usr)&userPwd=\(pwdCode)")  println("URL:  \(url)")  let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {     (data, response, error) in     println(NSString(data: data, encoding: NSUTF8StringEncoding)) }  //  task.setValue(<#value: AnyObject?#>, forKey: <#String#>) task.resume() 
like image 470
dhaval shah Avatar asked Nov 20 '14 14:11

dhaval shah


People also ask

What is NSURLSession in Swift?

Overview. The NSURLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.

How do I create a URLSession in Swift?

Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")! The next step is creating a data task, an instance of the URLSessionDataTask class. A task is always tied to a URLSession instance.

How do I use NSURLSession in Objective C?

NSURLSession introduces a new pattern to Foundation delegate methods with its use of completionHandler: parameters. This allows delegate methods to safely be run on the main thread without blocking; a delegate can simply dispatch_async to the background, and call the completionHandler when finished.


1 Answers

If you want to set the Content-Type of the request, you can create your own URLRequest, supplying your URL, specify the Content-Type header using setValue(_:forHTTPHeaderField:) and then issue the request with the URLRequest instead of the URL directly. And just set the httpBody to be that JSON and specify the httpMethod of POST:

let url = URL(string: "https://api/jobmanagement/PlusContactAuthentication")! var request = URLRequest(url: url) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")        // the expected response is also JSON request.httpMethod = "POST"  let dictionary = ["email": username, "userPwd": password] request.httpBody = try! JSONEncoder().encode(dictionary)  let task = URLSession.shared.dataTask(with: request) { data, response, error in     guard let data = data, error == nil else {         print(error ?? "Unknown error")                                 // handle network error         return     }      // parse response; for example, if JSON, define `Decodable` struct `ResponseObject` and then do:     //     // do {     //     let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)     //     print(responseObject)     // } catch let parseError {     //     print(parseError)     //     print(String(data: data, encoding: .utf8))   // often the `data` contains informative description of the nature of the error, so let's look at that, too     // } } task.resume() 

For Swift 2 rendition, see previous revision of this answer.

like image 113
Rob Avatar answered Dec 12 '22 22:12

Rob