Мне нужно использовать WP REST API в моем приложении ios, сейчас я использую Alamofire и SwiftyJSON.
func requestAlamofireToSwiftyJSON(_ url:String, completion: @escaping (JSON?, Bool, Success) -> ()) {
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = TIMEOUT
manager.session.configuration.timeoutIntervalForResource = TIMEOUT
manager.request(url).responseJSON { (response) -> Void in
switch response.result {
case .success:
guard let value = response.result.value else {
return
}
let json = JSON(value)
DLog(message:json)
completion(json, true, .loadOK)
case .failure(let error):
DLog(message:"failure")
DLog(message:"\n\nAuth request failed with error:\n \(error)")
if error._code == NSURLErrorTimedOut {
//HANDLE TIMEOUT HERE
completion(nil, false, .timeOut)
} else {
completion(nil, false, .loadError)
}
}
}
}
Журналы:
{
"code" : "rest_cannot_access",
"data" : {
"status" : 401
},
"message" : "Only authenticated users can access the REST API."
}
Мне нужно подтвердить свою подлинностьСогласно документации WP rest API , но я понятия не имею, как это сделать в SWIFT.
РЕДАКТИРОВАТЬ 1
Почти :) Почему этот код работает? В консоли отображается JSON.
var headers: HTTPHeaders = [
"Content-Type": "application/json"
]
let user = "userblablabla"
let password = "pwdblablabla"
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
Alamofire.request(url, headers:headers).responseJSON{ response in
DLog(message:url)
switch response.result {
case .success:
guard let value = response.result.value else {
return
}
let json = JSON(value)
DLog(message:json)
completion(json, true, .loadOK)
case .failure(let error):
DLog(message:"failure")
DLog(message:"\n\nAuth request failed with error:\n \(error)")
if error._code == NSURLErrorTimedOut {
//HANDLE TIMEOUT HERE
completion(nil, false, .timeOut)
} else {
completion(nil, false, .loadError)
}
}
}
И почему этот код не работает? Ошибка 401 (см. Выше)
let headers = [ "Content-Type": "application/json","X-Requested-With": "XMLHttpRequest","Cache-Control": "no-cache"]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = TIMEOUT
manager.session.configuration.timeoutIntervalForResource = TIMEOUT
manager.request(url).authenticate(user: "userblablabla", password: "pwdblablabla").responseJSON { (response) -> Void in
switch response.result {
case .success:
guard let value = response.result.value else {
return
}
let json = JSON(value)
DLog(message:json)
completion(json, true, .loadOK)
case .failure(let error):
DLog(message:"failure")
DLog(message:"\n\nAuth request failed with error:\n \(error)")
if error._code == NSURLErrorTimedOut {
//HANDLE TIMEOUT HERE
completion(nil, false, .timeOut)
} else {
completion(nil, false, .loadError)
}
}
}