Alamofire获取请求& JSON响应(Yelp API)

时间:2017-07-13 17:32:17

标签: ios json swift swifty-json yelp

我正在尝试使用Yelp的商业搜索API(https://www.yelp.ca/developers/documentation/v3/business_search)向Alamofire发送http get请求,但我在编写语法时遇到了麻烦。我是初学者,我第一次使用Alamofire,所以一些帮助将不胜感激!我也试图设置“术语”和“位置”参数。一旦完成,我希望通过SwiftyJSON解析并且不确定如何/在何处接收响应。

这是我目前的代码:

import UIKit
import Alamofire
import SwiftyJSON

private let reuseIdentifier = "cafeCell"

class CafeListCollectionViewController: 
UICollectionViewController,UICollectionViewDelegateFlowLayout {


override func viewDidLoad() {
    super.viewDidLoad()

    let requestParams: Parameters = ["term": "cafe", "location": "Montreal, QC"]

    //Http request

    let apiToContact = "https://api.yelp.com/v3/businesses/search"

    Alamofire.request(.GET, apiToContact, requestParams).responseJSON { (responseObject) -> Void in

        print(responseObject)

        if responseObject.result.isSuccess {
            let resJson = JSON(responseObject.result.value!)
            success(resJson)
        }
        if responseObject.result.isFailure {
            let error : NSError = responseObject.result.error!
            failure(error)
        }

    }

如果这听起来像一个简单的问题,我很抱歉。我是编程新手,非常感谢他们的帮助。非常感谢你!

1 个答案:

答案 0 :(得分:0)

问题可能在于您正在查看Swift 2示例,但在Swift 3中编写。这是Swift 3版本:

    let requestParams: Parameters = ["term": "cafe", "location": "Montreal, QC"]

    //Http request

    let apiToContact = "https://api.yelp.com/v3/businesses/search"


    Alamofire.request(apiToContact, method: .get, parameters: requestParams, encoding: URLEncoding.default, headers: nil).responseJSON { (responseObject) in
        print(responseObject)
        if responseObject.result.isSuccess {
            let resJson = JSON(responseObject.result.value!)
            success(resJson)
        }
        if responseObject.result.isFailure {
            let error : NSError = responseObject.result.error!
            failure(error)
        }
    }

您还需要来自Yelp的API令牌才能获得有效的响应。