gpt4 book ai didi

ios - Swift ios 如何获取解析的数据并将其分配给标签

转载 作者:行者123 更新时间:2023-11-28 06:01:09 25 4
gpt4 key购买 nike

我想知道如何快速从解析的 json 响应中获取每个名称。我想根据我的代码 cell.label.text = item.name 将响应的名称值分配给 cell.label.text。标签将根据 item.name 的数量自动执行,我想要的是它会根据 json 响应中有多少名称自动执行

 if indexPath.row == 0 {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddNewCell", for: indexPath as IndexPath) as! AddNewCollectionViewCell
cell.backgroundColor = unselectedCellColor // make cell more visible in our example project
return cell
} else {

let index = IndexPath(row: (indexPath.row - 1), section: 0)

let item = fetchedResultsController.object(at: index)

// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! GroceryItemCollectionViewCell
cell.buttonDelegate = self
cell.deleteButton.tag = indexPath.row - 1

cell.label.text = item.name
if item.isSelected {
cell.backgroundColor = selectedCellColor
} else {
cell.backgroundColor = unselectedCellColor
}
return cell
}

HTTP请求代码:

responseString = Optional("[{\"id\":51,\"name\":\"jelord\",\"desc\":\"ako si jelord\",\"reward\":\"1.00\",\"sched\":\"2018-04-06T11:37:09+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":53,\"name\":\"uuuuuu\",\"desc\":\"uuuuu\",\"reward\":\"8.00\",\"sched\":\"2018-03-06T10:49:54+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":54,\"name\":\"iiiii\",\"desc\":\"oiii\",\"reward\":\"67.00\",\"sched\":\"2018-02-06T10:51:34+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":55,\"name\":\"uuuu\",\"desc\":\"uuuu\",\"reward\":\"8.00\",\"sched\":\"2018-03-06T10:52:55+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":57,\"name\":\"uuuuuuuu\",\"desc\":\"uuuuuu\",\"reward\":\"8888.00\",\"sched\":\"2018-04-06T11:54:16.431000+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":61,\"name\":\"hhu\",\"desc\":\"yhh\",\"reward\":\"67.00\",\"sched\":\"2018-02-06T13:45:09+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":62,\"name\":\"huhu\",\"desc\":\"huu\",\"reward\":\"8.00\",\"sched\":\"2018-04-06T14:46:36.620000+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"}]")


code for getting the request.

var request = URLRequest(url: URL(string: "http://test.test:8000/api/v1/test/")!)

request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()

最佳答案

import UIKit
import Alamofire



class MenuCollectionViewController: UIViewController,
UICollectionViewDelegate, UICollectionViewDataSource {

var titleArray = [String]()

@IBOutlet var collectionView: UICollectionView!
@IBAction func signOutButtonIsPressed(_ sender: Any) {
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.showLoginScreen()
}
@IBOutlet var signoutButton: UIButton!
var items = [Item]()

override func viewDidLoad() {
super.viewDidLoad()

self.signoutButton.layer.cornerRadius = 3.0
demoApi()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

self.navigationController?.navigationBar.isHidden = true
self.navigationItem.hidesBackButton = true

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return titleArray.count
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
cell.nameLabel.text = titleArray[indexPath.row]
return cell
}



func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}

func demoApi() {
Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Response \(json)")
for item in json {

if let title = item["title"] as? String {
self.titleArray.append(title)
}

DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
break

case .failure(_):
print("Error")
break

}
}

}

}


class CollectionCell: UICollectionViewCell {

@IBOutlet weak var imgPhoto: UIImageView!
@IBOutlet weak var nameLabel: UILabel!


}

关于ios - Swift ios 如何获取解析的数据并将其分配给标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49687960/

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