我想发送post方法(登录用户),但是当我在运行时点击登录按钮时,我收到了这条消息:
我的班级:
typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()
let baseURL = "***********"
func login(body: [String: AnyObject],onCompletion: @escaping (JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPPostRequest(path: route,body: body, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func getCategories(onCompletion: @escaping (JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPGetRequest(path: route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func getRandomUser(onCompletion: @escaping (JSON) -> Void) {
let route = baseURL
makeHTTPGetRequest(path: route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
// MARK: Perform a GET Request
private func makeHTTPGetRequest(path: String, onCompletion: @escaping ServiceResponse) {
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, error as NSError?)
} else {
onCompletion(nil, error as NSError?)
}
})
task.resume()
}
// MARK: Perform a POST Request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: @escaping ServiceResponse) {
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
// Set the method to POST
request.httpMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
request.httpBody = jsonBody
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error as NSError?)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
}
在我的登录控制器中:
//after click on login button
let parameters = ["grant_type": "password",
"username": "test29@gmail.com",
"password": "1",
"client_id": "toS899lbMGolv8j24piz0JI38VUCi6Mvzru27iBA",
"client_secret":"lG14Tk7m2mGYLMvBndW2yFZ1NGRLNrriIPH6gw30gAnMAcFMa5xJE3wP8H 4SDHAK0ND5nKIoSLZskFQQ1knEYiaPC3i5LNutPJlusiMNiuvhUHWnbvTCjmNkuCBkGgqO"]
RestApiManager.sharedInstance.login(body: parameters as [String : AnyObject]) { (json: JSON) in
print(json)
}
答案 0 :(得分:0)
尝试将其放回主线程:
func login(body: [String: AnyObject],onCompletion:@escaping(JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPPostRequest(path: route,body: body, onCompletion: { json, err in
DispatchQueue.main.async {
onCompletion(json as JSON)
}
})
}