0
如何在Apache OpenWhisk上運行無服務器Swift函數期間使HTTP請求檢索並返回數據?在OpenWhisk上使用Swift進行HTTP請求?
無服務器雲平臺限制對運行時環境的訪問。這意味着您不能安裝額外的庫來幫助解決這個問題,例如https://github.com/Alamofire/Alamofire。
如何在Apache OpenWhisk上運行無服務器Swift函數期間使HTTP請求檢索並返回數據?在OpenWhisk上使用Swift進行HTTP請求?
無服務器雲平臺限制對運行時環境的訪問。這意味着您不能安裝額外的庫來幫助解決這個問題,例如https://github.com/Alamofire/Alamofire。
在Apache OpenWhisk的夫特運行時確實提供以下庫預裝:
的Kitura-net
庫提供了比Swift的網絡原語(URLSession)更高級別的HTTP請求。
下面是使用該庫從外部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的低級網絡原語手動完成。