gpt4 book ai didi

ios - 使用多个 Alamofire 链接请求填充 tableview

转载 作者:行者123 更新时间:2023-11-30 12:03:13 25 4
gpt4 key购买 nike

我是 Alamofire 的新人,我正在关注《IOS Apps with REST APIs》一书,其中我尝试解析 JSON 并填充 tableview,但问题是它在函数 loadGists 完成调用 Alamofire 链接请求之前调用 numberOfRowsInSection,所以我可以填充数组,然后相应地填充 TableView ,似乎 .responseArray 函数被称为异步函数或在 numberOfRowsInSection 函数之后调用。

var gists: [Gist]!

@IBOutlet var tabelView1: UITableView!
override func viewDidLoad() {
super.viewDidLoad()



self.tabelView1.delegate = self
self.tabelView1.dataSource = self
}

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
loadGists()
}


func loadGists() {
GitHubAPIManager.sharedInstance.getPublicGists() { result in
guard result.error == nil else {
print(result.error)
// TODO: display error
return
}
if let fetchedGists = result.value {
self.gists = fetchedGists
}
DispatchQueue.main.async {
self.tableView1.reloadData()
}

}
}

其中 GitHubAPIManager 类有:

class GitHubAPIManager: NSObject {


static let sharedInstance = GitHubAPIManager()

func getPublicGists(completionHandler: (Result<[Gist]>) -> Void) {
Alamofire.request(GistRouter.GetPublic())
.responseArray { (response) in
completionHandler(response.result)
}
}
}

responseArray 是:

public func responseArray<T: ResponseJSONObjectSerializable>(
completionHandler: Response<[T]) -> Self {
let serializer = ResponseSerializer<[T]> { request, response, data, error in
guard error == nil else {
return .Failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed,
failureReason: failureReason)
return .Failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response,
responseData, error)
switch result {
case .Success(let value):
let json = SwiftyJSON.JSON(value)
var objects: [T] = []
for (_, item) in json {
if let object = T(json: item) {
objects.append(object)
}
}
return .Success(objects)
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: serializer, completionHandler: completionHandler)
}

对于表格 View :

    func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return gists.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let gist = gists[indexPath.row]
cell.textLabel!.text = gist.description
cell.detailTextLabel!.text = gist.ownerLogin

return cell
}

GistRouter 是:

enum GistRouter: URLRequestConvertible {

static let baseURLString:String = "https://api.github.com"

case getPublic()




var method: HTTPMethod {

switch self {

case .getPublic:
return .get
}
}

func asURLRequest() throws -> URLRequest {

let result: (path: String, parameters: [String: AnyObject]?) = {

switch self {
case .getPublic:
return ("/gists/public", nil)
}
}()


let URL = Foundation.URL(string: GistRouter.baseURLString)!




var UrlRequest: URLRequest? = URLRequest(url: URL.appendingPathComponent(result.path))

UrlRequest = try URLEncoding.default.encode(UrlRequest!, with: result.parameters)


UrlRequest?.httpMethod = method.rawValue

return UrlRequest!
}

要点类别是:

class Gist: ResponseJSONObjectSerializable  {


var id: String?
var description: String?
var ownerLogin: String?
var ownerAvatarURL: String?
var url: String?


required init(json: SwiftyJSON.JSON) {
self.description = json["description"].string
self.id = json["id"].string
self.ownerLogin = json["owner"]["login"].string
self.ownerAvatarURL = json["owner"]["avatar_url"].string
self.url = json["url"].string
}
required init() {
}

}

我尝试过 DispatchQueue.global(qos: .utility).async 并且还 让 semaphore = DispatchSemaphore(value: 0) 以不同的方式但没有运气,我需要先完成 Alamofire 链式请求,然后调用 numberOfRowsInSection,请帮忙。

最佳答案

它对我有用:

var gists = [Gist]() {
didSet {

self.tabelView1.reloadData()

}
}

关于ios - 使用多个 Alamofire 链接请求填充 tableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46963490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com