'swift errors when trying to do post request to api
Can someone help me understand what's wrong with my code? my api has params username and password. api is working fine everywhere except swift. I want to post data so I get response from my api but code below is just not working and idk what's wrong. I will attach log which is generated after I press login button.
*
LOG: 2022-03-31 02:01:07.131507+0200 Hiyori[33451:1487997] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics 2022-03-31 02:01:07.146594+0200 Hiyori[33451:1487997] Task <75DC051E-47A2-4D48-932C-B2E679A0C510>.<1> HTTP load failed, 330/0 bytes (error code: -1017 [4:-1]) 2022-03-31 02:01:07.148275+0200 Hiyori[33451:1487997] Task <75DC051E-47A2-4D48-932C-B2E679A0C510>.<1> finished with error [-1017] Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo={_kCFStreamErrorCodeKey=-1, NSUnderlyingError=0x6000013be4c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x600003e24410 [0x1de715af0]>{length = 16, capacity = 16, bytes = 0x100201bbbc7261110000000000000000}, _kCFStreamErrorCodeKey=-1, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <75DC051E-47A2-4D48-932C-B2E679A0C510>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <75DC051E-47A2-4D48-932C-B2E679A0C510>.<1>" ), NSLocalizedDescription=cannot parse response, NSErrorFailingURLStringKey=https://api.hiyori.cz/Login, NSErrorFailingURLKey=https://api.hiyori.cz/Login, _kCFStreamErrorDomainKey=4} The operation couldn’t be completed. (Hiyori.AuthenticationError error 0.)
import Foundation
enum AuthenticationError: Error {
case invalidCredentials
case custom(errorMessage: String)
}
enum NetworkError: Error {
case invalidURL
case noData
case decodingError
}
struct LoginRequestBody: Codable {
let username: String
let password: String
}
struct LoginResponse: Codable {
let token: String?
let message: String?
let success: Bool?
}
class Webservice {
func login(username: String, password: String, completion: @escaping (Result<String, AuthenticationError>) -> Void) {
guard let url = URL(string: "https://api.hiyori.cz/Login") else {
completion(.failure(.custom(errorMessage: "URL is not correct")))
return
}
let body = LoginRequestBody(username: username, password: password)
let Bearer = "Bearer token here...."
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(Bearer, forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "'Content-Type: multipart/form-data'")
request.httpBody = try? JSONEncoder().encode(body)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
completion(.failure(.custom(errorMessage: "No data")))
return
}
try! JSONDecoder().decode(LoginResponse.self, from: data)
guard let loginResponse = try? JSONDecoder().decode(LoginResponse.self, from: data) else {
completion(.failure(.invalidCredentials))
return
}
guard let token = loginResponse.token else {
completion(.failure(.invalidCredentials))
return
}
completion(.success(token))
}.resume()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
