Alamofire API 连接和 Swift

Posted

技术标签:

【中文标题】Alamofire API 连接和 Swift【英文标题】:Alamofire API connection and Swift 【发布时间】:2017-07-21 01:29:29 【问题描述】:

我在向 EatStreet API 发送 AlamoFire 请求时遇到问题。我有一个 API 密钥,并且我已经正确导入了 Alamofire。

https://developers.eatstreet.com/endpoint/search

下面是他们将为您创建 API URL 字符串的网站的链接。

尽管如此,我仍然没有成功

这是示例字符串

curl -X GET \
 -H 'X-Access-Token: __API_EXPLORER_AUTH_KEY__' \
 'https://api.eatstreet.com/publicapi/v1/restaurant/search?latitude=40.718293&longitude=-74.002276&method=pickup&pickup-radius=2'

下面是我的 api 和 Alamofire 请求的示例代码。对于结果的值,它不断返回 false。任何帮助表示赞赏

import UIKit
import Firebase
import FirebaseDatabase

import FirebaseAuth
import Alamofire
import SwiftyJSON

class ViewController: UIViewController 

override func viewDidLoad() 
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    tap.cancelsTouchesInView = false

    view.addGestureRecognizer(tap)

    let apiToContact = "\\ -H 'X-Access-Token: f6565a0360167144' \\'https://api.eatstreet.com/publicapi/v1/restaurant/search?latitude=40.718293&longitude=-74.002276&method=pickup&pickup-radius=2'"
    Alamofire.request(apiToContact).validate().responseJSON()  response in
        switch response.result 
        case .success:
            if let value = response.result.value 
                let json = JSON(value)

                // Do what you need to with JSON here!
                // The rest is all boiler plate code you'll use for API requests
                print(json)

            
        case .failure(let error):
            print(error)
        
    





//Calls this function when the tap is recognized.
func dismissKeyboard() 
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)


override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.




【问题讨论】:

【参考方案1】:

如Alamofire Docs 中所述,您应该发送带有标头参数的请求

let headers: HTTPHeaders = [
    "X-Access-Token": "API_EXPLORER_AUTH_KEY"
]

let url = "https://api.eatstreet.com/publicapi/v1/restaurant/search?latitude=40.718293&longitude=-74.002276&method=pickup&pickup-radius=2"

Alamofire.request(url, headers: headers).responseJSON  response in
    print(response)

【讨论】:

@HiDungLing 很好,请标记为正确答案 ;)【参考方案2】:

另一种解决方案如下所示。这里会自动生成查询参数并附加到 URL。这种方法可以防止查询参数中的一些特殊字符转义。试试下面的

 func sendRequest() 
    let headers = ["X-Access-Token":"eatstreetToken"]
    let parameters:[String:Any] = ["latitude":40.718293,"longitude":-74.002276, "method":"pickup","pickup-radius":2]
    let apiToContact = "https://api.eatstreet.com/publicapi/v1/restaurant/search"

    let request = Alamofire.request(apiToContact, method: .get, parameters: parameters, encoding: URLEncoding.queryString, headers: headers)
    request.validate().responseJSON()  response in
        print(response.response?.url ?? "malformed url")
        switch response.result 
        case .success(let value):
              print(value)
        case .failure(let error):
            print(error)
        
    

【讨论】:

如果我希望编码为 json 怎么办 看起来不像eatstreet为该字符串返回的内容 我刚刚通过在eatstreet开发者门户上创建新帐户自己尝试了上述代码,并且打印在我的控制台上的响应是正确的

以上是关于Alamofire API 连接和 Swift的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire 和 api 密钥有问题

为啥没有网络连接时 Alamofire 需要这么长时间才能超时?

Alamofire 网络连接丢失

使用 alamofire 通过 iOS 应用程序连接 Windows SSL 服务器

Alamofire 向 API 'NSInvalidArgumentException' 发送请求

使用 Alamofire 从 API 获取响应