还有其他人可以帮助我知道在swift中调用函数的方法是什么,接收JSON集合响应? 我在viewController.swift中调用ApiClient()。getList()函数,此函数调用我的API并在apiClient.swift中接收JSON响应,最后我想将此JSON响应分配给self.result变量in viewController.swift。
我的代码是:
viewController.swift
import UIKit
class ClubsViewController: UIViewController, UITableViewDataSource{
var results: [JSON]? = []
@IBOutlet var tableview:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.loadClubsObjects()
}
func loadClubsObjects(){
self.results = ApiClient().getList() <--- here is the call
self.tableview.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.results?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("clubsObjectCell") as! ClubsTableViewCell
cell.clubsObject = self.results?[indexPath.row]
return cell
}
}
ApiClient.swift
import Foundation
import Alamofire
class ApiClient {
func getList() -> [JSON] {
var URL = NSURL(string: "https://api.com/v1/clubs")
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/json")
mutableURLRequest.HTTPMethod = "GET"
mutableURLRequest.setValue("Bearer R01.iNsG3xjv/r1LDkhkGOANPv53xqUFDkPM0en5LIDxx875fBjdUZLn1jtUlKVJqVjsNwDe1Oqu2WuzjpaYbiWWhw==", forHTTPHeaderField: "Authorization")
let manager = Alamofire.Manager.sharedInstance
let request = manager.request(mutableURLRequest)
request.responseJSON { (request, response, json, error) in
if (json != nil){
var jsonObj = JSON(json!)
if let data = jsonObj["hits"].arrayValue as [JSON]?{
return data
}
}
}
}
并且apiClient.swift中的错误是
返回数据 - &gt; [JSON]无法转换为Void
答案 0 :(得分:3)
getList
的定义方式是它应该返回[JSON]
个对象。但它不能这样做,因为responseJSON
是一个异步方法(即responseJSON
的完成闭包直到你从getList
返回后才被调用。
您必须使用自己的completionHandler
模式。例如,getList
不会返回任何内容,,而是需要一个完成处理程序参数:
func getList(completionHandler: ([JSON]) -> ()) {
let URL = NSURL(string: "https://api.com/v1/clubs")
let mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/json")
mutableURLRequest.HTTPMethod = "GET"
mutableURLRequest.setValue("Bearer R01.iNsG3xjv/r1LDkhkGOANPv53xqUFDkPM0en5LIDxx875fBjdUZLn1jtUlKVJqVjsNwDe1Oqu2WuzjpaYbiWWhw==", forHTTPHeaderField: "Authorization")
let manager = Alamofire.Manager.sharedInstance
let request = manager.request(mutableURLRequest)
request.responseJSON { response in
if let json = response.result.value {
var jsonObj = JSON(json)
if let hits = jsonObj["hits"].arrayValue as [JSON]? {
completionHandler(hits)
}
}
}
}
你会像以下一样调用它:
let apiClient = ApiClient()
func loadClubsObjects() {
apiClient.getList() { hits in
// use hits here
self.results = hits
self.tableView.reloadData()
}
// but not here
}
注意,我倾向于不让API客户端成为loadClubsObjects
的局部变量,而是如上所示的类属性。做任何你想做的事情,但它让我觉得这是一个更合乎逻辑的生命周期。
如果您想处理错误,可以更改完成处理程序的闭包,以便(a)JSON
命中数组是可选的; (b)添加一个可选的错误对象。然后更改getList
以传回这些可选值:
func getList(completionHandler: ([JSON]?, NSError?) -> ()) {
let URL = NSURL(string: "https://api.com/v1/clubs")
let mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/json")
mutableURLRequest.HTTPMethod = "GET"
mutableURLRequest.setValue("Bearer R01.iNsG3xjv/r1LDkhkGOANPv53xqUFDkPM0en5LIDxx875fBjdUZLn1jtUlKVJqVjsNwDe1Oqu2WuzjpaYbiWWhw==", forHTTPHeaderField: "Authorization")
let manager = Alamofire.Manager.sharedInstance
let request = manager.request(mutableURLRequest)
request.responseJSON { response in
if let json = response.result.value {
var jsonObj = JSON(json)
if let hits = jsonObj["hits"].arrayValue as [JSON]? {
completionHandler(hits, nil)
} else {
let jsonError = NSError(domain: "mydomain", code: MyErrorCode.HitsNotFound, userInfo: nil) // create whatever sort of error object you think is appropriate if `hits` was not found
completionHandler(nil, jsonError)
}
} else {
completionHandler(nil, response.result.error)
}
}
}
然后,当您调用它时,您可以检查JSON对象数组是否为nil
,如果它是nil
,则查看NSError
对象。