我遇到了JSON问题。 我写了一个名为Book.swift的课程
class Book {
var id: Int?
var name: String?
var author: String?
var translator: String?
var publisher: String?
var genre: String?
var yop: String?
var pageTotal: String?
var description: String?
var cover_url: String?
}
在我的ViewController中,我使用Alamofire和SwiftyJSON调用JSON
class BookSingleController: UIViewController, UIScrollViewDelegate {
var book = Book()
func URLRequest(url:String) {
let URLRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
URLRequest.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
Alamofire.request(.GET, url)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
if let jsonData = response.result.value {
dispatch_async(dispatch_get_main_queue(), {
let json = JSON(jsonData)
if let item = json["books"].array {
self.book = Book()
self.book.name = item[0]["title"].string
self.book.author = item[0]["author"]["name"].string
self.book.translator = item[0]["translator"]["name"].string
self.book.cover_url = item[0]["cover_url"].string
self.book.yop = item[0]["year_of_publish"].string
self.book.genre = item[0]["genres"].string
self.book.pageTotal = item[0]["number_of_page"].string
self.book.publisher = item[0]["publisher"].string
self.book.description = item[0]["description"].string
}
return
})
self.tableRefresh()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
case .Failure(let error):
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
print(error)
}
}
}
我有另一种方法可以将book变量分配给tableView单元格的标签
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.nameLabel.text = self.book.name
return cell
}
但是self.book.name在tableView方法中返回nil.can你们告诉我,我的错误在哪里?感谢
修改 将self.tableView.reloadData()放入dispatch_async(dispatch_get_main_queue()但仍返回nil
func tableRefresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tabelView.reloadData()
})
}