【发布时间】:2021-09-11 07:22:08
【问题描述】:
当我尝试在 tableview 单元格中显示作者姓名时,我收到错误,例如“无法将 [String] 类型的值分配给 String 类型”,因为我将作者元素声明为数组。由于作者元素的API响应是一个数组,我不知道如何声明它。请帮助我
API 响应
{
"kind": "books#volumes",
"totalItems": 2361,
"items": [
{
"kind": "books#volume",
"id": "_eyJAAAAQBAJ",
"etag": "MJbx6HKC3B4",
"volumeInfo": {
"title": "A Quilting Life",
"subtitle": "Creating a Handmade Home",
**"authors": [
"Sherri McConnell"
],**
"publisher": "C&T Publishing Inc",
"publishedDate": "2013-02-12",
struct VolumeInfo : Codable {
let authors : [String]
let publisher : String?
let subtitle : String?
let title : String?
}
代码:
class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
var items : [Items] = []
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.jpeg")!)
fetchBooks { data in
self.items.self = data
DispatchQueue.main.async {
self.bookTableView.reloadData()
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell",for:indexPath) as! BookCell
cell.bookAuthor.text = items[indexPath.row].volumeInfo.title
cell.bookCategory.text = items[indexPath.row].volumeInfo.publisher
cell.bookAuthor.text = items[indexPath.row].volumeInfo.authors
return cell
}
func fetchBooks(comp : @escaping ([Items])->()){
let urlString = "https://www.googleapis.com/books/v1/volumes?q=quilting"
let url = URL(string: urlString)
guard url != nil else {
return
}
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { [self] (data, response, error) in
//check for errors
if error == nil && data != nil{
//parse json
do {
let result = try JSONDecoder().decode(Book.self, from: data!)
comp(result.items)
print("Retrieved books are \(items)")
}
catch {
print("Error in json parcing\(error)")
}
}
}
//make api call
dataTask.resume()
}
}
【问题讨论】:
-
一个叫“书”的人从何而来?
标签: ios json swift parsing codable