无法从api获取访问令牌

时间:2018-04-30 10:09:38

标签: ios iphone swift api http

enter image description here我是Swift的新手,我遇到了一个问题。欢迎任何帮助和建议,我也见过Alomofire,但由于一些错误我无法设置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&#34 ;;           " ERROR_DESCRIPTION" ="强制性的'grant_type'参数丢失。&#34 ;;       }

这些是我应该发布到API的参数,在postman中它可以正常工作但我的代码在编译器中根本不起作用。

enter image description here

3 个答案:

答案 0 :(得分:0)

你太复杂了

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)
        }

    }

试试这个。

这就是你所需要的。如果你有任何疑问,请在这里询问。

答案 1 :(得分:0)

按照此链接使用CocoaPods安装Alamofire

https://www.raywenderlich.com/156971/cocoapods-tutorial-swift-getting-started enter 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)
            }
    }
}

答案 2 :(得分:0)

您需要在发送请求时对查询中的登录名和密码参数进行编码。让我们创建一个单独的Network类,它具有loginRequest(username:password)函数,该函数使用用户名和密码参数向服务器发出API请求。 login方法有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类的实例,并使用用户名和密码params调用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)
            }
        }
    }