2017-09-05 24 views
-1

代码在这里使用Yelp的融合API中迅速应用不认证,连续接收“VALIDATION_ERROR”

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

你没有张贴整个代码,但也有一些细微的修改你的代码工作:

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() 
+0

是的它结束了一个愚蠢的错误,我经过一个URL到dataTask功能,而不是请求。以'res'开头的词太多 – ggworean