我目前正在發送我的json數據到Dictionary
在相同的ViewController
。我想將它發送到一個名爲Users的類。數據正在顯示在TableView
上。發送json數據到單獨的類和顯示在tableView
import UIKit
class Users: NSObject {
var name: String?
}
class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var userList = [Users]()
@IBOutlet weak var myTableView: UITableView!
final let urlString = "https://api.lookfwd.io/v1/test/users"
var namesArray = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
myCell.nameLabel.text = namesArray[indexPath.row]
return myCell
}
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithTask()
// Do any additional setup after loading the view.
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
if let dataArray = (jsonData! as AnyObject).value(forKey: "users") as? NSArray {
for data in dataArray{
// let user = Users()
// user.setValuesForKeys(data as! [String : Any])
// self.userList.append(user)
if let dataDict = data as? NSDictionary {
if let title = dataDict.value(forKey: "name") {
self.namesArray.append(title as! String)
}
}
print(jsonData!)
}
}
OperationQueue.main.addOperation({
self.myTableView.reloadData()
})
print(jsonData!)
}).resume()
}
}
之前添加用戶到用戶列表,您需要將您的JSON轉換爲用戶模型。 – Bala
你的問題不清楚。你是否試圖在一個viewcontroller中執行API調用,並想在另一個控制器中顯示數據? – Praveenkumar
不,我想發送數據到我的用戶類,然後在我的桌面視圖中的FriendsViewController顯示名稱 – user8000557