我想为数组赋值并在表视图中显示该值。 我通过webservice使用webservice代码获取值。 值得越来越完美,我使用print语句进行测试,它完美地显示了这些值。但是当我将这些值分配给表视图时,它什么也没显示。这是我的代码。请帮帮我
let con = "http://192.168.10.10/Hand.svc/";
var list = [String]()
var answer:String = ""
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: con+"getlocation?email=saim@gmail.com")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "getlocationResult")
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"=")
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
self.list = st1.components(separatedBy: ";")
print (self.list[0])
i += 1
}
}
catch
{
}
}
}
}
task.resume()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return(list.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
return(cell)
}
}
答案 0 :(得分:1)
DispatchQueue.main.async
- 用于更新UI的原因,因为网络呼叫是后台队列。
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "getlocationResult")
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"=")
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
self.list = st1.components(separatedBy: ";")
print (self.list[0])
i += 1
}
DispatchQueue.main.async(execute: { () -> Void in
self.yourTableViewName.reloadData()
})
}
catch
{
}
vadian评论;
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return list.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
return cell
}
}