Skip to content

Instantly share code, notes, and snippets.

@DineshKachhot
Created September 7, 2019 02:06
Show Gist options
  • Save DineshKachhot/5eeaecdc600d52d75a1f9744410320a8 to your computer and use it in GitHub Desktop.
Save DineshKachhot/5eeaecdc600d52d75a1f9744410320a8 to your computer and use it in GitHub Desktop.
NSURLSession POST request - Swift 4.2
guard let urlEncodedString = (AppConstants.URL.sendDeviceTokekn).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return
}
let url = URL(string: urlEncodedString)!
let urlRequest = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
urlRequest.setValue("Application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("Application/json", forHTTPHeaderField: "Accept")
urlRequest.httpMethod = "POST"
let params: [String : Any] = ["txDeviceToken":token, "tDeviceOs":2]
guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) else {
return
}
urlRequest.httpBody = httpBody
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) in
guard let data = data, error == nil else {
print("error=\(error ?? "Could not save Device Token" as! Error)")
return
}
do {
let tokenResponse = try JSONDecoder().decode(TokenResponse.self, from: data)
print(tokenResponse.message)
} catch {
print("json error: \(error)")
}
}
task.resume()
import Foundation
struct TokenResponse: Codable {
var message:String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment