我在SWIFT编程很新,我不是熟悉的Web服务。我想创建一个iOS移动应用程序的诗歌。有没有一种方法可以在Swift 3 Xcode 8中首先完成异步任务?
我能够检索JSON编码的数据,但我的问题是,我可以在这里不会转移到我的tableview。当我运行它时,我认为问题是由于异步任务。既然是在异步任务,当name.count仍然是0,因为在执行委托FUNC后的任务也只是运行的tableview(numberOfRows)的委托功能被执行。这就是为什么我无法在我的TableView中看到我的数据......我希望有人能帮助我。我GOOGLE了,并尝试完成处理程序(我不知道它用于什么),我试图将其更改为同步,这导致我出错。非常感谢!
import UIKit
import Foundation
class TimelineViewController: UIViewController {
@IBOutlet weak var contentTableView: UITableView!
var name = [String]()
var bio = [String]()
@IBOutlet weak var oPostBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getPoems()
}
func getPoems()
{
let url:NSURL = NSURL(string: "http://192.168.1.6/Test/feed1.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(url:url as URL)
request.httpMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main){(response, data, error) in }
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("Error = \(error)")
return
}
do {
print("Response=\(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Response data = \(responseString)")
//Converting response to NSDictionary
var json: NSDictionary!
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//getting the JSONArray poems from the response
let returnPoems: NSArray = json["returnPoems"] as! NSArray
print(returnPoems);
//looping through all the json objects in the array teams
for i in 0 ..< returnPoems.count{
let aObject = returnPoems[i] as! [String : AnyObject]
self.name.append(aObject["fullName"] as! String)
self.bio.append(aObject["Bio"] as! String)
//displaying the data
print("Fullname -> ", self.name)
print("Bio ->", self.bio)
print("===================")
print("")
}
}
catch {
print("ERROR: \(error)")
}
}
task.resume()
}
}
extension TimelineViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = contentTableView.dequeueReusableCell(withIdentifier: "PoemCell")
cell?.textLabel?.text = name[indexPath.row]
cell?.detailTextLabel?.text = bio[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return name.count
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
}
}
在你完成块,当你完成建设'name'和'bio'阵列,调用'DispatchQueue.main.async {self.tableView.reloadData( )}'刷新表。 – Rob
@Rob非常感谢你Rob!不能相信我已经花了数小时的时间了。此外,我做了你所说的,你是对的!工作正常。再次感谢你! – Nadz