在您的完成区块中,当您完成构建
name
和
bio
reloadData
从主队列:
DispatchQueue.main.async {
self.tableView.reloadData()
}
我还提出了一些其他建议:
-
NSURLConnection
密码它正在执行冗余请求,而您没有对响应执行任何操作;另外,它是一个弃用的API,应该删除;
-
你应该使用
URL
NSURL
;
-
你应该使用
URLRequest
NSMutableURLRequest
;
-
String
而不是
NSString
;
-
你应该使用Swift
Array
和
Dictionary
而不是
NSArray
和
NSDictionary
-
您的签名
didSelectRowAt
不正确。使用
IndexPath
不
NSIndexPath
-
您正在更新
名称
生物
来自
URLSession
后台队列。这不是线程安全的。您可以通过从主队列中更新这些来解决这个问题,以避免需要进行额外的同步。
-
Poem
. 这使代码更加简单。它也开辟了新的可能性(例如,如果您想对
大堆您将如何更新单独的
生物
struct Poem {
let name: String
let bio: String
init?(dictionary: [String: Any]) {
guard let name = dictionary["fullName"] as? String,
let bio = dictionary["Bio"] as? String else {
print("Did not find fullName/Bio")
return nil
}
self.name = name
self.bio = bio
}
}
class TimelineViewController: UIViewController {
@IBOutlet weak var contentTableView: UITableView!
var poems = [Poem]()
@IBOutlet weak var oPostBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getPoems()
}
func getPoems() {
let url = URL(string: "http://192.168.1.6/Test/feed1.php")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("Error = \(error?.localizedDescription ?? "Unknown error")")
return
}
if let response = response {
print("Response=\(response)")
}
if let responseString = String(data: data, encoding: .utf8) {
print("Response data = \(responseString)")
}
// Converting response to Dictionary
guard let json = try? JSONSerialization.jsonObject(with: data),
let responseObject = json as? [String: Any],
let returnPoems = responseObject["returnPoems"] as? [[String: Any]] else {
print("did not find returnPoems")
return
}
print(returnPoems)
// dispatch the update of model and UI to the main queue
DispatchQueue.main.async {
self.poems = returnPoems.flatMap { Poem(dictionary: $0) }
self.contentTableView.reloadData()
}
}
task.resume()
}
}
extension TimelineViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = contentTableView.dequeueReusableCell(withIdentifier: "PoemCell", for: indexPath)
let poem = poems[indexPath.row]
cell.textLabel?.text = poem.name
cell.detailTextLabel?.text = poem.bio
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return poems.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// let indexPath = tableView.indexPathForSelectedRow! // why do this? ... the indexPath was passed to this function
// let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell // why do this? ... you don't care about the cell ... go back to you model
let poem = poems[indexPath.row]
// do something with poem, e.g.
print(poem)
}
}