在swift应用程序中使用Yelp Fusion API无法进行身份验证,不断收到“VALIDATION_ERROR”

时间:2017-09-05 20:20:34

标签: ios swift yelp

此处代码

let link = "https://api.yelp.com/oauth2/token"
guard let url = URL(string: link) else { return }

// Headers
let headers = [
  "content-type": "application/x-www-form-urlencoded"
]

guard let clientID = infoPlist(withKey: "YELP_API_CLIENT_ID"),
  let clientSecret = infoPlist(withKey: "YELP_API_CLIENT_SECRET") else { return }

let body = "client_id=\(clientID)&client_secret=\(clientSecret)&grant_type=client_credentials"

var request = URLRequest.init(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = body.data(using: .utf8)

据我所知,这应该有效。根据我读过的所有内容,这是使用Yelp Fusion / v3进行身份验证的正确过程。

1 个答案:

答案 0 :(得分:1)

您没有发布整个代码,但稍微修改一下您的代码就可以了:

let appId = "xxx"
let appSecret = "yyy"
let link = "https://api.yelp.com/oauth2/token"
let url = URL(string: link)!

let bodyData = "client_id=\(appId)&client_secret=\(appSecret)&grant_type=client_credentials".data(using: .utf8)!

// Headers
let headers = [
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": "\(bodyData.count)"
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = bodyData

typealias JSON = [String:Any]
URLSession.shared.dataTask(with: request) { (data, response, error) in

    guard let data = data,
        let httpResponse = response as? HTTPURLResponse,
        httpResponse.statusCode == 200 else {
            print(error!)
            return
    }

    if let responseJSON = try? JSONSerialization.jsonObject(with:data, options:[]),
        let parsedJSON = responseJSON as? JSON {
        let token = parsedJSON["access_token"]
        let exipration = parsedJSON["expires_in"]
    }
}.resume()