0

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

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

4

1 回答 1

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]
}

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

于 2017-08-11T16:55:30.307 回答