我正在構建一個應用程序,需要使用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)
}
我這麼想嗎?