POST method in Swift4 urlSession Decodable not working(What goes wrong here?) - swift4

I am trying to post 2 parameters (email: and password) to get a response from the server with detailed user information, I build API to handle this and get a good response using Postman, but when I tried to implement this with Swift4 new urlsession JSON decode and encode, it keeps failing and I got error on decoding the response data.
this my JSON response when using Postman:
{
"error": "false",
"message": "downloaded",
"UserInfo": {
"id": 5,
"email": "abc#hotmail.com",
"lastname": "Bence",
"name": "Mark",
"phone": "1234567",
"add1": "333",
"add2": "444",
"city": "ott",
"postalcode": "tttttt"
}
}
My struct file:
import UIKit
struct loginPost: Encodable {
let email: String
let password: String
}
struct User: Decodable {
let error: String?
let message: String?
let UserInfo: [UserData]
}
struct UserData: Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
My Function
func downloadJson() {
let url = URL(string: http://192.168.0.10/api/login_hashed.php)
guard let downloadURL = url else { return }
//POST Req
var request = URLRequest(url: downloadURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newpost = loginPost(email: "abc#hotmail.com", password: "123456")
do {
let jsonBody = try JSONEncoder().encode(newpost)
request.httpBody = jsonBody
print(jsonBody)
}catch{
print("some error")
}
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong with url")
return
}
print("downloaded..")
do
{
let decoder = JSONDecoder()
let downloaduser = try decoder.decode(User.self, from: data)
self.logmessage = downloaduser.message!
print(self.logmessage)
DispatchQueue.main.async {
// self.tableView.reloadData()
}
} catch {
print("something wrong with decode")
}
}.resume()
}

I have figured it out finally, thanks,.
I just want to mention the cause of this error and share my experience.
The main cause is the way you send JSON and receive the incoming response. you should know exactly how the data look in order to create your struct the acceptable way.
My return data is just simple 2 line of text and array of text, my struct was:
import UIKit
struct loginPost: Encodable {
let email: String
let password: String
}
struct User: Decodable {
let error: String?
let message: String?
let UserInfo: [UserData]
}
struct UserData: Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
my mistake on line 18
let UserInfo: [UserData]
it should be
let UserInfo: UserData?
without the square bracket.
one more important point, always try to catch the decode error and it's dicription by implementing }catch let JsonErr {, it will give you exactly why the decode not working.
in my case:
downloaded.. something wrong after downloaded
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath:
[h2h.User.(CodingKeys in _E33F61CC43E102744E4EF1B7E9D7EDDE).UserInfo],
debugDescription: "Expected to decode Array but found a
dictionary instead.", underlyingError: nil))
And make sure to make your server API to accept JSON format application/json and
decode what you send in order to receive what you looking for;
php code service API
$UserData = json_decode(file_get_contents("php://input"), true);

Simplest and easy way to decode the json.
MUST TRY
struct Welcome: Codable {
let error, message: String?
let userInfo: UserInfo?
enum CodingKeys: String, CodingKey {
case error, message
case userInfo = "UserInfo"
}
}
// MARK: - UserInfo
struct UserInfo: Codable {
let id: Int?
let email, lastname, name, phone: String?
let add1, add2, city, postalcode: String?
}
After that in your code , when you get response from api then write
let decoder = JSONDecoder()
let obj = try! decoder.decode(Welcome.self, from: jsonData!)
Print(obj)

List item
This Will work Are You Creating Model Is Wrong
struct loginPost: Encodable {
let email: String
let password: String
}
struct Users:Codable {
var error:String?
var message:String?
var UserInfo:UserDetails?
}
struct UserDetails:Codable {
let id: Int?
let email: String?
let lastname: String?
let name: String?
let phone: String?
let add1: String?
let add2: String?
let city: String
let postalcode: String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
let url = URL(string: "http://192.168.0.10/api/login_hashed.php")
guard let downloadURL = url else { return }
//POST Req
var request = URLRequest(url: downloadURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newpost = loginPost(email: "abc#hotmail.com", password: "123456")
do {
let jsonBody = try JSONEncoder().encode(newpost)
request.httpBody = jsonBody
print(jsonBody)
}catch{
print("some error")
}
URLSession.shared.dataTask(with: request) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong with url")
return
}
print("downloaded..")
do
{
let decoder = JSONDecoder()
let downloaduser = try decoder.decode(Users.self, from: data)
// self.logmessage = downloaduser.message!
// print(self.logmessage)
DispatchQueue.main.async {
// self.tableView.reloadData()
}
} catch {
print("something wrong with decode")
}
}.resume()
}
}

Related

Encoding string data back to JSON is giving an error

I've removed jsonCallback ( and ) from the URL https://www.apple.com/support/systemstatus/data/developer/system_status_en_US.js using the below.
var dataString = String(data: data, encoding: .utf8)
dataString = dataString?.replacingOccurrences(of: "jsonCallback(", with: "")
dataString = dataString?.replacingOccurrences(of: ");", with: "")
let json = dataString?.data(using: .utf8)
let jsonData = try JSONEncoder().encode(json)
The error I'm getting back
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
I can't find where the mismatch is happening at because when I look at dataString and piece it back together the JSON decoding model appears to match.
Here's the full code:
func fetchSystemStatus() async -> [SystemStatus] {
guard let url = URL(string: systemStatusURL) else {
return []
}
do {
let (data, response) = try await URLSession.shared.data(from: url)
// This is commented out data to try and gather developer system status
var dataString = String(data: data, encoding: .utf8)
dataString = dataString?.replacingOccurrences(of: "jsonCallback(", with: "")
dataString = dataString?.replacingOccurrences(of: ");", with: "")
let json = dataString?.data(using: .utf8)
let jsonData = try JSONEncoder().encode(json)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
print("\(#function) \(response)")
return []
}
let statusData = try JSONDecoder().decode(SystemStatus.self, from: jsonData)
return [statusData]
} catch {
print("\(#function) \(error)")
return []
}
}
Model:
// MARK: - SystemStatus
struct SystemStatus: Codable {
let services: [Service]
enum CodingKeys: String, CodingKey {
case services = "services"
}
}
// MARK: - Service
struct Service: Codable, Identifiable {
let id = UUID()
let redirectURL: String?
let events: [Event]
let serviceName: String
enum CodingKeys: String, CodingKey {
case redirectURL = "redirectUrl"
case events = "events"
case serviceName = "serviceName"
}
}
// MARK: - Event
struct Event: Codable {
let usersAffected: String
let epochStartDate: Int
let epochEndDate: Int
let messageID: String
let statusType: String
let datePosted: String
let startDate: String
let endDate: String
let affectedServices: [String]?
let eventStatus: String
let message: String
enum CodingKeys: String, CodingKey {
case usersAffected = "usersAffected"
case epochStartDate = "epochStartDate"
case epochEndDate = "epochEndDate"
case messageID = "messageId"
case statusType = "statusType"
case datePosted = "datePosted"
case startDate = "startDate"
case endDate = "endDate"
case affectedServices = "affectedServices"
case eventStatus = "eventStatus"
case message = "message"
}
}
This should work:
let statusData = try JSONDecoder().decode(SystemStatus.self, from: Data(json!))
or
let statusData = try JSONDecoder().decode(SystemStatus.self, from: Data(dataString!.utf8))
What's your issue:
let jsonData = try JSONEncoder().encode(json)
But json here is Data, so if you call JSONEncoder on it, by default, it will use Base64, so it won't be like the JSON you expect.
But json already is correct.

URLRequest Error "The given data was not valid JSON."

Trying to make a POST request with headers and params
Codeable code:
struct WelcomeMessage: Codable {
let receivedMessages: [ReceivedMessage]
}
// MARK: - ReceivedMessage
struct ReceivedMessage: Codable, Identifiable {
let ackID: String
let message: Message
let id = UUID()
enum CodingKeys: String, CodingKey {
case ackID
case message
}
}
// MARK: - Message
struct Message: Codable {
let data, messageID, publishTime: String
enum CodingKeys: String, CodingKey {
case data
case messageID
case publishTime
}
}
Service code:
class GetMessages: ObservableObject {
private var project_id: String = "redacted"
private var project_name: String = "redacted"
#Published var messages = [ReceivedMessage]()
func getMessages() {
guard let url = URL(string: "https://pubsub.googleapis.com/v1/projects\(project_id)/subscriptions\(project_name):pull") else {return}
var request = URLRequest(url: url)
let parameters : [String:Any] = [
"returnImmediately": false,
"maxMessages": 10]
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer ya29.redacted", forHTTPHeaderField: "Authorization")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {print(error!.localizedDescription); return }
// guard let data = data else {print("empty data"); return }
let theData = try! JSONDecoder().decode(WelcomeMessage.self, from: data!)
print(theData)
DispatchQueue.main.async {
self.messages = theData.receivedMessages
}
}
.resume()
}
}
The response to the request should return some JSON data that looks like:
{
"receivedMessages": [
{
"ackId": "UdfdsfdsfdsfdsfdgfhgfjJHGkjkjhKgjhgjFhgfDFgfdgDFGDFdfgFDGfd",
"message": {
"data": "//BASE-64 ENCODED STRING HERE",
"messageId": "4130086024457484",
"publishTime": "2022-02-16T15:03:49.372Z"
}
}
]
}
Error message as above, not sure why it's saying the data is not valid JSON?
Additional opinionated question...Should I just be using AlamoFire for this?
If the json response you show is correct, then in ReceivedMessage change ackID to ackId (note the small "d"),
or use
enum CodingKeys: String, CodingKey {
case ackID = "ackId"
case message
}
Similarly for messageID in Message.

Parsing JSON from URL ends up with an Error - Swift 5

I am trying to write a function in swift that gets data from an URL JSON, and allocate it to variables in swift.
This is the function:
func getBikeData(){
guard let url = URL(string: "https://api.citybik.es//v2/networks/baksi-bisim") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
//Decode JSON Response Data
let model = try decoder.decode(Station.self,
from: dataResponse)
print(model.freeBikes) //Output - 1221
} catch let parsingError {
print("Error", parsingError)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
This is the struct's that I added, with the data I need:
// MARK: - Station
struct Station: Codable {
let emptySlots: Int
let extra: Extra
let freeBikes: Int
let id: String
let latitude, longitude: Double
let name, timestamp: String
enum CodingKeys: String, CodingKey {
case emptySlots
case extra
case freeBikes
case id, latitude, longitude, name, timestamp
}
}
// MARK: - Extra
struct Extra: Codable {
let slots: Int
let status: Status
let uid: String
}
enum Status: String, Codable {
case active = "Active"
}
This is the error I have been receiving:
Error keyNotFound(CodingKeys(stringValue: "emptySlots", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"emptySlots\", intValue: nil) (\"emptySlots\").", underlyingError: nil))
This is the first time I was working with a JSON file, and maybe I am missing something very simple. Please help.
Here is how to decode all the json data into a swift struct:
import Foundation
struct Stations: Codable {
let company: [String]
let href: String
let id: String
let location: LocationJson
let name: String
let stations: [Station]
}
struct Station: Codable {
let empty_slots: Int
let extra: Extra
let free_bikes: Int
let id: String
let latitude: Double
let longitude: Double
let name: String
let timestamp: String
}
struct ResponseJSON: Codable {
let network: Stations
}
struct LocationJson: Codable {
let city: String
let country: String
let latitude: Double
let longitude: Double
}
struct Extra: Codable {
let slots: Int
let status: String
let uid: String
}
func getBikeData(){
guard let url = URL(
string: "https://api.citybik.es//v2/networks/baksi-bisim"
) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data, error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
//Decode JSON Response Data
let model = try decoder.decode(
ResponseJSON.self, from: dataResponse
)
print(model) //Output - 1221
} catch let parsingError {
print("Error", parsingError)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
getBikeData()
Error keyNotFound(CodingKeys(stringValue: "emptySlots", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"emptySlots\", intValue: nil) (\"emptySlots\").", underlyingError: nil))
The above error will occur if you are trying to decode a JSON object that doesn't have that key and the key is not marked as an optional.
You can either fix the server-end so emptySlots is returned or mark emptySlots as an optional in your struct:
struct Station: Codable {
let emptySlots: Int?

Error while doing phone number verification using twilio in swift

I want to verify phone number by getting one time password. But I am getting some error. Please look into the code bellow and help me to resolve it. I am using Twilio for mobile verification. And Alamofire for API request. But the error I am getting like:-
Authentication Error - No credentials provided.
The data couldn’t be read because it isn’t in the correct format
My code is:-
Here is my model class: -
...struct SendVerificationCode: Codable {
let status: String?
let payee: String?
let dateUpdated: Date?
let sendCodeAttempts: [SendCodeAttempt]?
let accountSid, to: String?
let amount: Int?
let valid: Bool?
let lookup: Lookup?
let url: String?
let sid: String?
let dateCreated: Date?
let serviceSid, channel: String?
enum CodingKeys: String, CodingKey {
case status, payee
case dateUpdated = "date_updated"
case sendCodeAttempts = "send_code_attempts"
case accountSid = "account_sid"
case to, amount, valid, lookup, url, sid
case dateCreated = "date_created"
case serviceSid = "service_sid"
case channel
}
}
struct Lookup: Codable {
let carrier: Carrier?
}
struct Carrier: Codable {
let mobileCountryCode, type: String?
let errorCode: String?
let mobileNetworkCode, name: String?
enum CodingKeys: String, CodingKey {
case mobileCountryCode = "mobile_country_code"
case type
case errorCode = "error_code"
case mobileNetworkCode = "mobile_network_code"
case name
}
}
struct SendCodeAttempt: Codable {
let channel, time: String?
}...
Api Request:-
...func sendcode(mobileWithCode: String, completion: #escaping sendTwillioVerificationCodeCompletion) {
let url = URL(string: SEND_TWILIO_VERIFICATION_CODE)
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.addValue(userNameData, forHTTPHeaderField: "Username")
urlRequest.addValue(PasswordData, forHTTPHeaderField: "Password")
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest).responseJSON { (response) in
if let error = response.result.error {
debugPrint(error.localizedDescription)
completion(nil)
return
}
guard let data = response.data else { return completion(nil)}
Common.sharedInstance().printRequestOutput(data: data)
let jsonDecoder = JSONDecoder()
do {
let clear = try jsonDecoder.decode(SendVerificationCode.self, from: data)
completion(clear)
} catch {
debugPrint(error.localizedDescription)
completion(nil)
}
}
}...
But i am getting error:-
{"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}
"The data couldn’t be read because it isn’t in the correct format."
Also i have tried the following code:-
import Foundation
semaphore = DispatchSemaphore (value: 0)
let parameters = "To=+919778882332&Channel=sms"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: myUrl)!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(requestData, forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
But i am getting error like
"Invalid parameter"
Twilio developer evangelist here.
It looks as though your code is trying to call the Twilio API directly from the device and that you weren't setting your Account SID or Auth Token in that.
The issue here is that you should not store or access your auth token from within your application. That would make your account sid and auth token vulnerable to be stolen and then used to abuse your account.
Instead, you should create a server side application that talks to the Twilio API and then call that from your application.
As Jamil pointed out, there is a blog post you can follow on performing phone verification in iOS with Twilio Verify and Swift and I recommend you go through that. It includes an example server side application to call the Twilio Verify API built in Python, but you could build your own too.
Here is sample code:
import UIKit
class ViewController: UIViewController {
static let path = Bundle.main.path(forResource: "Config", ofType: "plist")
static let config = NSDictionary(contentsOfFile: path!)
private static let baseURLString = config!["serverUrl"] as! String
#IBOutlet var countryCodeField: UITextField! = UITextField()
#IBOutlet var phoneNumberField: UITextField! = UITextField()
#IBAction func sendVerification() {
if let phoneNumber = phoneNumberField.text,
let countryCode = countryCodeField.text {
ViewController.sendVerificationCode(countryCode, phoneNumber)
}
}
static func sendVerificationCode(_ countryCode: String, _ phoneNumber: String) {
let parameters = [
"via": "sms",
"country_code": countryCode,
"phone_number": phoneNumber
]
let path = "start"
let method = "POST"
let urlPath = "\(baseURLString)/\(path)"
var components = URLComponents(string: urlPath)!
var queryItems = [URLQueryItem]()
for (key, value) in parameters {
let item = URLQueryItem(name: key, value: value)
queryItems.append(item)
}
components.queryItems = queryItems
let url = components.url!
var request = URLRequest(url: url)
request.httpMethod = method
let session: URLSession = {
let config = URLSessionConfiguration.default
return URLSession(configuration: config)
}()
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
do {
let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
print(jsonSerialized!)
} catch let error as NSError {
print(error.localizedDescription)
}
} else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
}
For more please check this link: Link.

Data fetched via postman and URLSession is different in here http://173.249.20.137:9000/apiapp/coupon

http://173.249.20.137:9000/apiapp/coupon GET method .
when I request via URLSession and Postman I get two different results. Actually postman data is correct, but the URL session has always the same response whether I add or delete data it is not going to update. Can anybody please give a look. if it is happening with me only or something wrong at the backend server.
I have tested requesting data with URLSession.shared and postman.
I actually like to have the data I get via postman through URLSession request too.
func getAvailableCoupons(urlString:String, completion: #escaping (_
product: Any, _ error: Error?) -> Void){
guard let url = URL(string: urlString) else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response,
error) in
let jsonDecoder = JSONDecoder()
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
let statusCode = (response as! HTTPURLResponse).statusCode
let responseJSON = try? JSONSerialization.jsonObject(with: dataResponse, options: [])
if let responseJSON = responseJSON as? [String: Any] {
if statusCode == 200 {
do {
let jsonData = try JSONSerialization.data(withJSONObject: responseJSON, options: [])
let responseData = try jsonDecoder.decode(CoupensResponseModel.self, from:jsonData)
completion(responseData, nil)
} catch let error {
print("error when parshing json response \(error)")
completion(error, nil )
}
} else if statusCode == 404{
completion(" 404 not found", nil )
} else {
print("fatal error \(error?.localizedDescription ?? "big errror")")
}
}
}
task.resume()
}
import Foundation
// MARK: - CoupensResponseModel
struct CoupensResponseModel: Codable {
let couponDetails: [CouponDetail]?
enum CodingKeys: String, CodingKey {
case couponDetails = "coupon_details"
}
}
// MARK: - CouponDetail
struct CouponDetail: Codable {
let id: Int?
let vouchersusageSet: [VouchersusageSet]?
let couponCode: String?
let minimumSpend: Int?
let expiryDate, createdDate: String?
let discountPrice, discountPercent: Int?
let discountBasis: DiscountBasis?
let couponImage: String?
let couponType: String?
enum CodingKeys: String, CodingKey {
case id
case vouchersusageSet = "vouchersusage_set"
case couponCode = "coupon_code"
case minimumSpend = "minimum_spend"
case expiryDate = "expiry_date"
case createdDate = "created_date"
case discountPrice = "discount_price"
case discountPercent = "discount_percent"
case discountBasis = "discount_basis"
case couponImage = "coupon_image"
case couponType = "coupon_type"
}
}
enum DiscountBasis: String, Codable {
case amount = "amount"
case percent = "percent"
}
// MARK: - VouchersusageSet
struct VouchersusageSet: Codable {
let id: Int?
let itemObj: ItemObj?
let voucherObj: Int?
let sectionObj, categoryObj: Int?
}
// MARK: - ItemObj
struct ItemObj: Codable {
let id: Int?
let code, productName: String?
let productPrice, discountedPrice: Int?
let productDescription, itemImage: String?
let categoryObj: CouponCategoryObj?
enum CodingKeys: String, CodingKey {
case id, code
case productName = "product_name"
case productPrice = "product_price"
case discountedPrice = "discounted_price"
case productDescription = "product_description"
case itemImage = "item_image"
case categoryObj
}
}
// MARK: - CouponCategoryObj
struct CouponCategoryObj: Codable {
let id: Int?
let categoryCode, categoryName: String?
let categoryImage: CouponJSONNull?
let sectionObj: Int?
enum CodingKeys: String, CodingKey {
case id
case categoryCode = "category_code"
case categoryName = "category_name"
case categoryImage = "category_image"
case sectionObj
}
}
// MARK: - Encode/decode helpers
class CouponJSONNull: Codable, Hashable {
public static func == (lhs: CouponJSONNull, rhs: CouponJSONNull) ->
Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(CouponJSONNull.self,
DecodingError.Context(codingPath: decoder.codingPath,
debugDescription:
"Wrong type for CouponJSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
Try the following method
let headers = [
"Cache-Control": "no-cache",
]
let request = NSMutableURLRequest(url: NSURL(string: "http://173.249.20.137:9000/apiapp/coupon")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let string = String(data: data!, encoding: .utf8) ?? ""
print(string)
}
})
dataTask.resume()
Please look on response both are same.
Postman response :
https://jsoneditoronline.org/?id=7b94ef69a3344164aa4a96423fdbf9db
Code response :
https://jsoneditoronline.org/?id=6e5a7d221d9c4c818f1d46fc893031fe