【问题标题】:Making HTTP request using Swift on OpenWhisk?在 OpenWhisk 上使用 Swift 发出 HTTP 请求?
【发布时间】:2017-08-11 16:55:30
【问题描述】:

如何在 Apache OpenWhisk 上运行的无服务器 Swift 函数期间发出 HTTP 请求以检索和返回数据?

无服务器云平台限制对运行时环境的访问。这意味着您无法安装额外的库来帮助解决此问题,例如 https://github.com/Alamofire/Alamofire

【问题讨论】:

    标签: swift openwhisk serverless-architecture


    【解决方案1】:

    Apache OpenWhisk 上的 Swift 运行时预装了以下库:

    Kitura-net 库为发出 HTTP 请求提供了比 Swift 的网络原语 (URLSession) 更高级别的 API。

    这是一个使用该库从外部 JSON API 返回数据作为函数响应的示例。

    import KituraNet
    import Foundation
    import SwiftyJSON
    
    func httpRequestOptions() -> [ClientRequest.Options] {
      let request: [ClientRequest.Options] = [ 
        .method("GET"),
        .schema("https://"),
        .hostname("api.coindesk.com"),
        .path("/v1/bpi/currentprice.json")
      ]
    
      return request
    }
    
    func currentBitcoinPricesJson() -> JSON? {
      var json: JSON = nil
      let req = HTTP.request(httpRequestOptions()) { resp in
        if let resp = resp, resp.statusCode == HTTPStatusCode.OK {
          do {
            var data = Data()
            try resp.readAllData(into: &data)
            json = JSON(data: data)
          } catch {
            print("Error \(error)")
          }
        } else {
          print("Status error code or nil reponse received from App ID server.")
        }
      }
      req.end()
    
      return json
    }
    
    func main(args: [String:Any]) -> [String:Any] {
      guard let json = currentBitcoinPricesJson() else {
          return ["error": "unable to retrieve JSON API response"]
      }
    
      guard let rate = json["bpi"]["USD"]["rate_float"].double else {
        return [ "error": "Currency not listed in Bitcoin prices" ]
      }
    
      return ["bitcoin_to_dollars": rate]
    }
    

    仍然可以使用 Swift 的低级网络原语手动发出 HTTP 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2021-10-26
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多