我正在尝试将函数get()的结果获取到TableView。此函数中的结果来自http post。所以我使用了nsmutableurl等,我得到了n可以在输出控制台中看到的数据,现在希望它出现在我的tableview中。我该怎么做?
我有一堆代码,我设法获取数据(可以在我的输出控制台中看到),现在我正试图将这些数据加载到表视图中。如何在表中传递此数据?
func get(){
let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl/somefile.php")!)
request.HTTPMethod = "POST"
let postString = "id=\(cate_Id)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
i need the count of the rows here
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
land want to display the data inside each cell
}
最佳答案
因为您没有提供任何关于http请求结果的信息,所以我试图以“一般方式”回答您。
一般情况下,您会得到一个响应,作为所需数据的字典数组。为了简单起见:假设您请求字符串,那么您必须这样做:
let myStringArray: [String] = []
在您的http响应块中,您接受您的响应,请注意!这段代码完全取决于您的响应树。我不知道你有什么反应,因为你没有提供。
if let JSON = response.result.value {
let myString = String((JSON.valueForKey("stringWithinMyResonseTree"))!)
myStringArray.append(myString)
self.tableView.reloadData()
}
然后您的行数与:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myStringArray.count
}
这取决于你想用它做什么。例如,如果单元格中有一个标签,并希望在其上显示字符串的值,则可以创建一个
UITableViewCell
子类并将其称为例如MyCell
。在MyCell
中,您创建一个标签的出口,如下所示:class MyCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
然后需要返回
UITableView
子类并用所需的字符串填充标签。func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
let string = myStringArray[indexPath.row]
cell.myLabel.text = string
return cell
}
不要忘记在接口生成器属性中设置单元格标识符。
您的请求需要一个包含一个字典的数组,但您将其转换为字符串。因此,请使用以下函数而不是
get()
函数:func download() {
let requestURL: NSURL = NSURL(string: "http://myurl/somefile.php")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
let grouID = String(json.valueForKey("group_id"))
let name = String(json.valueForKey("NAME"))
print("grouID = \(grouID)")
print("name = \(name)")
print("debug: this code is executed")
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
若要调试问题,请创建异常断点: