Created
September 7, 2019 02:06
-
-
Save DineshKachhot/5eeaecdc600d52d75a1f9744410320a8 to your computer and use it in GitHub Desktop.
NSURLSession POST request - Swift 4.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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