2017-08-11 48 views

回答

1

在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的低級網絡原語手動完成。