ios 无法从API获取访问令牌

0yg35tkg  于 12个月前  发布在  iOS
关注(0)|答案(3)|浏览(185)

x1c 0d1x的数据
我是Swift的新手,我刚刚遇到了一个问题。欢迎任何帮助和建议,我也见过Alamofire,但我无法设置Alamofire,因为一些错误,我也需要Alamofire的帮助:|

request.addValue("application/json", forHTTPHeaderField:   
      "Accept")
    request.addValue("application/x-www-form-urlencoded", 
      forHTTPHeaderField:   "Content-Type")
    let postString = ["grant_type"  : "password" ,
                      "username"    : EntPhoneNumber.text! ,
                      "password"    : EntPassword.text! ,] as [String : 
 Any]
    do {
        
        
        request.httpBody = try JSONSerialization.data(withJSONObject: 
 postString)
    }catch let error {
        print(error.localizedDescription)
        DisplayMessage(UserMessage: "Something went wrong , please try 
 again!")
        return
    }
    
    let task = URLSession.shared.dataTask(with: request)
    {
        (data : Data? , response : URLResponse? , error : Error?) in
        
        self.removeActivtyIndicator(activityIndicator: 
 MyActivityIndicator)
        
        
        
        if error != nil
        {
            self.DisplayMessage(UserMessage: "1Could not successfully 
 perform this request , please try again later.")
            print("error = \(String(describing : error))")
            return
        }
        
        
        
        // let's convert response sent from a 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 userID = parseJSON["grant_type"] as? String
                print("access_token : \(String(describing: userID))");
                
                if userID == nil
                {
                    //display an alert dialog with a friendly error 
message
                    self.DisplayMessage(UserMessage: "2Could not 
successfully perform this request , please try later.")
                    return
                }
                else
                {
                    self.DisplayMessage(UserMessage: "3successfully 
loged in.")
                }
            }

字符串
...
正如你所看到的,这是我的代码,我向API发出请求以获取access_token,但我收到一个错误:
{error =“invalid_request”;“error_description”=“缺少必需的”grant_type“参数。"; }
这些是我应该发布到API的参数,在Postman中它可以正常工作,但我的代码在编译器中根本不工作。


zdwk9cvp

zdwk9cvp1#

点击此链接使用CocoaPods安装Alamofire
https://www.raywenderlich.com/156971/cocoapods-tutorial-swift-getting-startedenter link description here的数据库
我为API请求创建了这个自定义方法。

func request(_ method: HTTPMethod
    , _ URLString: String
    , parameters: [String : AnyObject]? = [:]
    , headers: [String : String]? = [:]
    , completion:@escaping (Any?) -> Void
    , failure: @escaping (Error?) -> Void) {

    Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
        .responseJSON { response in

            switch response.result {
            case .success:
                completion(response.result.value!)
            case .failure(let error):
                failure(error)
            }
    }
}

字符串

oxcyiej7

oxcyiej72#

在发送请求时,您需要在查询中对登录和密码参数进行编码。让我们创建一个单独的Network类,该类具有loginRequest(username:password)函数,该函数使用用户名和密码参数向服务器发出API请求。登录方法具有closure,该方法返回userId字符串或Error。

class Networking {

    enum NetworkError: Error {
        case parsingData
        case jsonParsing
        case emptyData
        case apiError(error: Error)
    }

    func parseJSON(from data: Data) throws -> Any {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            return json
        } catch {
            return error
        }
    }

    func loginRequest(username: String, password: String, completion: @escaping (String?, NetworkError?) -> ()) {

        var request = URLRequest(url: URL(string: "api.nahadeh.com/connect/token")!)
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        let queryParams = "grant_type=password&username=\(username)&password=\(password)"
        request.httpBody = queryParams.data(using: .utf8, allowLossyConversion: false)

        URLSession.shared.dataTask(with: request) { (data, response, error) in

            guard error != nil else {
                completion(nil, NetworkError.apiError(error: error!))
                return
            }

            guard let data = data else {
                return completion(nil, NetworkError.emptyData)
            }

            do {
                let json = try self.parseJSON(from: data) as! [String: Any]
                guard let accessToken = json["access_token"] as? String else {
                    completion(nil, NetworkError.jsonParsing)
                    return
                }
                completion(accessToken, nil)
            } catch {
                completion(nil, NetworkError.jsonParsing)
            }
        }.resume()
    }
}

字符串
现在,从UIViewController子类中,您可以创建Networking类的示例,并使用用户名和密码参数调用login方法

class LoginViewController: UIViewController {

    let networking = Networking()

    func login(username: String, password: String) {

        networking.loginRequest(username: username, password: password) { (token, error) in

            if let token = token {
                print(token)
                self.displayMessage("Successfully loged in. Go to home screen")
                return
            }

            if let nError = error {
                switch nError {
                case .jsonParsing:
                    self.displayMessage("jsonParsingError")
                case .emptyData:
                    self.displayMessage("emptyData")
                case .apiError(let error):
                    print(error.localizedDescription)
                    self.displayMessage("Could not successfully perform this request , please try later.")
                case .parsingData:
                    self.displayMessage("parsingData")
                }
            }
        }
    }

    func displayMessage(_ message: String, completion: (() -> Void)? = nil) {
        let alert = UIAlertController(title: "Message", message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: completion)
    }
}


使用Alamofire可以很容易地发出API请求,只需传递参数,它就会为您完成工作

func loginRequest(username: String, password: String, completion: @escaping (String?, Error?) -> ()) {

        let params: [String: String] = [
            "grant_id": "password",
            "username": username,
            "password" : password
        ]

        Alamofire.request("api.nahadeh.com/connect/token", method: .post, parameters: params, encoding: .httpBody, headers: nil).validate().response { (response) in
            switch response.result {
            case .success(let value):
                let accessToken = value["access_token"]
                completion(accessToken, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }

lhcgjxsq

lhcgjxsq3#

你把事情弄得太复杂了

let postString = ["grant_type"  : "password" ,
                      "username"    : EntPhoneNumber.text! ,
                      "password"    : EntPassword.text! ,] as [String :
                        Any]

    Alamofire.request(URL, method: .post, parameters: postString, encoding: URLEncoding.methodDependent, headers: nil).responseJSON { response in

        if let json = response.result.value {
            print("Response: ",json)
        }

    }

字符串
试试这个.
这就是你所需要的。如果你有任何疑问,问这里。

相关问题