I am trying to make posts to my Wordpress blog via Swift. I am using the Wordpress REST API with Java Web Token (JWT) authentication. The first step is to pass the user credentials to the server using the HTTP POST method. The server then returns a JSON Object containing the JWT token needed for authentication. I can get this all working using a REST API program like Postman, but I am having trouble with the Swift code.
My credentials are sent just fine and the server returns some data, but I am having trouble getting the token from this data.
This Swift code was generated by the Postman app:
import Foundation
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache",
]
let parameters = [
"username": "myUsername",
"password": "myPassword"
] as [String : Any]
let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "https://myDomain/wp-json/jwt-auth/v1/token")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
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 httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
When I do the HTTP POST command in Postman I get back this JSON:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvY3F1aWNrLmNhIiwiaWF0IjoxNTQ3Njc3MDMzLCJuYmYiOjE1NDc2NzcwMzMsImV4cCI6MTU0ODI4MTgzMywiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMyJ9fX0.DgxmmSFKnEdXuWi5EiBk1BpFvWrD57KIE8TiWazId-4",
"user_email": "myEmail",
"user_nicename": "myUsername",
"user_display_name": "myUsername"
}
Is there anyway to get this same result using Swift? I imagine that this is being returned by the session.dataTask method, I just have no idea how to parse it.