I'm trying to follow Last.fm's tutorial to consume their API in an iOS app (using Swift), but I don't know what's wrong with my code. They ask to do something called Last.fm method signature which I'm not understanding how to insert into my program. Here is the link to the tutorial I try to follow: https://www.last.fm/api/mobileauth
Here is my current code:
import UIKit
struct LoginRequestBody: Codable {
var username: String
var password: String
var api_key: String
var api_sig: String
}
enum AuthenticationError: Error {
case invalidCredentials
case custom(errorMessage: String)
}
class APIService {
func requestAPI(username: String, password: String, api_key: String, api_sig: String) {
guard let url = URL(string: "http://www.last.fm/api/auth/?api_key=xxx") else {
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let body = LoginRequestBody(username: username, password: password, api_key: api_key, api_sig: api_sig)
let bodyStr = [
"username": "\(body.username)",
"password": "\(body.password)",
"api_key": "\(body.api_key)",
"api_sig": "\(body.api_sig)"]
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: bodyStr, options: .fragmentsAllowed)
let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in
guard let data = data, error == nil else {
return
}
do {
let response = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
print(response)
} catch {
print(error)
}
}
task.resume()
}
}