无法从我的HTTPrequest返回数据,并且我也无法使完成处理程序正常工作。因此,请协助我解决这个问题:
static func Login(urlExtension: String, userName: String, userPassword: String) -> String
{
let url = baseUrl?.appendingPathComponent(urlExtension)
var request = URLRequest(url: url!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
let dataOpt = "Username=\(userName)&Password=\(userPassword)&grant_type=password"
request.httpBody = dataOpt.data(using: String.Encoding.ascii, allowLossyConversion: false)
let task = URLSession.shared.dataTask(with: request){
(data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
return
}
//Let's convert response sent from server side code to a NSDictionary object:
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print(json)
if let parseJSON = json {
let accessToken = parseJSON["access_token"] as? String
let userName = parseJSON["userName"] as? String
let saveAccessToken: Bool = KeychainWrapper.standard.set(accessToken!, forKey: "accessToken")
let saveUserName: Bool = KeychainWrapper.standard.set(userName!, forKey: "userName")
}
else{
}
}catch{
}
}
return "test"
}
这是被调用的方法,我无法从URLSession.shared.data内部的响应中返回解析的访问令牌,
我尝试实现完成处理程序,但是我不知道实现它是否出错,还是无法在模拟器中正确测试
此方法在视图控制器之外的API管理器中实现,并且baseURL var是全局变量