因此,我使用AFNetworking 2.0发送帖子并将请求发送到服务。由于我在整个应用程序中都在使用它,所以我使用以下两个函数创建了一个包装类:
// An HTTP GET call
func get(urlString:String, body:AnyObject?, completion:(data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation) -> ())
{
var operation = self.GET(urlString,
parameters: body,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
completion(data: (responseObject), error: nil, operation: operation)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
completion(data: nil, error: error, operation: operation)
}
)
}
// An HTTP POST call
func post(urlString: String, body: AnyObject?, completion:(data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation) -> ())
{
var operation = self.POST(urlString,
parameters: body,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
completion(data: (responseObject), error: nil, operation: operation)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
completion(data: nil, error: error, operation: operation)
}
)
}问题是当我在TableViewController中使用它们时。由于这些方法正在运行异步(我相信),所以在接收数据之前创建了该表。这是TVC:
class ShopViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
var stores = [PartnerStore]()
override func viewDidLoad() {
super.viewDidLoad()
self.loadStores()
// Do any additional setup after loading the view, typically from a nib.
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int
{
return 3;
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
// placeholder value
return 1;
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell = tableView.dequeueReusableCellWithIdentifier("PartnerShopCell") as PartnerStoreTableViewCell
cell.storeLogoImageView.image = UIImage();
cell.storeNameLabel.text = self.stores[indexPath.row].name;
return cell;
}
func loadStores()
{
var networkManager:APIClient = APIClient.sharedInstance
networkManager.get("partner_stores/", body: nil, completion: {
(data:AnyObject?, error:NSError?, operation: AFHTTPRequestOperation) in
self.stores = data as [PartnerStore]
println("Data \(self.stores)");
self.tableView.reloadData()
if (!error) {
} else {
println(error)
println (operation.response.statusCode)
}
});
}
}当我运行这个应用程序时,我会得到一个“超出范围的数组索引”错误,因为在调用cellForRowAtIndexPath时,get调用还没有完成。
我在考虑使用GCD,但我不确定这是否会有帮助。任何建议都会很好。
发布于 2014-08-04 12:33:57
您获得错误Array index out of range是因为您硬编码了委托方法中的行数,它应该是datasource的计数,这样当下载完成并重新加载tableView数据时,计数将被更新,因为您是异步加载的:
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return self.stores[indexPath.row].count
}https://stackoverflow.com/questions/25118371
复制相似问题