2016-08-02 72 views
2

我正在構建一個應用程序,需要使用Siesta框架向API端點https://thecountedapi.com/api/counted發出GET請求。端點返回JSON數組,就像https://api.github.com/users/ebelinski/repos這樣的端點,在Siesta示例Github Browser中使用。因此,我試圖用我所說的方式讓我的應用程序使用Siesta。我創建一個服務:如何爲包含JSON數組的API端點創建Siesta轉換器?

let API = Service(baseURL: "https://thecountedapi.com/api") 

然後在application:didFinishLaunchingWithOptions我的終點變壓器:

API.configureTransformer("/counted") { 
    ($0.content as JSON).arrayValue.map(Incident.init) 
} 

如果事件是與發生在一個JSON對象的初始化一個結構。

然後在我的視圖控制器,我創建了一個資源:

let resource = API.resource("/counted") 

viewDidLoad

resource.addObserver(self) 

viewWillAppear

resource.loadIfNeeded() 

然後,我有以下功能在我的VC中聽取更改:

func resourceChanged(resource: Resource, event: ResourceEvent) { 
    print(resource.jsonArray) 

    if let error = resource.latestError { 
    print(error.userMessage) 
    return 
    } 

    if let content: [Incident] = resource.typedContent() { 
    print("content exists") 
    incidents = content 
    } 

    print(incidents.count) 
} 

但是當我運行我的應用程序時,我得到了混合結果。 print(resource.jsonArray)只是打印[],我有一個錯誤消息Cannot parse server response,如果我設置Siesta.enabledLogCategories = LogCategory.detailed,我可以看到錯誤消息[Siesta:StateChanges] Siesta.Resource(https://thecountedapi.com/api/counted)[] received error: Error(userMessage: "Cannot parse server response", httpStatusCode: nil, entity: nil, cause: Optional(Siesta.Error.Cause.WrongTypeInTranformerPipeline(expectedType: "JSON", actualType: "__NSCFArray", transformer: Siesta.ResponseContentTransformer<SwiftyJSON.JSON, Swift.Array<TheCountedViewer.Incident…

如果我註釋掉整個變壓器,我已經取得了一些成功,print(resource.jsonArray)從端點輸出正確的數組。所以我的變壓器必須是錯誤的以某種方式,但我認爲我使用基本相同的變壓器在Github上的瀏覽器:

service.configureTransformer("https://stackoverflow.com/users/*/repos") { 
    ($0.content as JSON).arrayValue.map(Repository.init) 
} 

我這麼想嗎?

回答

0

的關鍵線索,你的問題是埋在(也許不是最好helfpul)日誌消息:

Siesta.Error.Cause.WrongTypeInTranformerPipeline 
    expectedType: "JSON" 
    actualType: "__NSCFArray" 

它說,你的變壓器預期JSON輸入類型,這是有道理的 - 你說了這麼多與($0.content as JSON)。然而,它得到類型__NSCFArray,這是NSArray的祕密內部支持類型。換句話說,它期望得到一個SwiftyJSON值,但它得到了NSJSONSerialization的原始輸出。

爲什麼? GithubBrowser項目包括一個NSDict/NSArray → SwiftyJSON transformerconfigures in the parsing stage。該項目中的模型變壓器都依賴於它。

要以同樣的方式在項目中使用SwiftyJSON,你需要包括示例項目在你那個變壓器:

private let SwiftyJSONTransformer = 
    ResponseContentTransformer 
    { JSON($0.content as AnyObject) } 

,然後設置你的服務時:

service.configure { 
    $0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"]) 
} 

(請注意,您可能要創建ResponseContentTransformertransformErrors: true,如果你有興趣的錯誤。)


使用SwiftyJSON,這是不太漂亮,但需要較少的設置,是在每個單獨的響應變壓器手動包裹在JSON事物的另一種方法:

service.configureTransformer("https://stackoverflow.com/users/*/repos") { 
    JSON($0.content as AnyObject).arrayValue.map(Incident.init) 
} 
相關問題