【发布时间】:2016-03-08 15:52:03
【问题描述】:
我正在尝试将数据传递到 tableView 的单元格中。网络通信有效,因为项目列表出现在第一个单元格中。
例如列表如下:sensor1, sensor2, sensor3,.... 但应该是这样的:
传感器1
传感器2
...
这就是我解析 CSV 文件的方式
struct ParseCVS {
func parseURL (contentsOfURL: NSURL, encoding: NSStringEncoding) -> ([String])?{
let rowDelimiter = ","
var nameOfSensors:[String]?
do {
let content = try String(contentsOfURL: contentsOfURL, encoding: encoding)
print(content)
nameOfSensors = []
let columns:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]
for column in columns {
let values = column.componentsSeparatedByString(rowDelimiter)
if let nameOfSensor = values.first {
nameOfSensors?.append(nameOfSensor)
}
}
}
catch {
print(error)
}
return nameOfSensors
}
}
这是我的 TableViewController
class TableViewController: UITableViewController {
// Array which will store my Data
var nameOfSensorsList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
guard let wetterURL = NSURL(string: "http://wetter.htw-berlin.de/phpFunctions/holeAktuelleMesswerte.php?mode=csv&data=1")
else {
return
}
let parseCSV = ParseCVS()
nameOfSensorsList = parseCSV.parseURL(wetterURL, encoding: NSUTF8StringEncoding)!
tableView.estimatedRowHeight = 100.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameOfSensorsList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MenuTableViewCell
cell.nameLabel?.text = nameOfSensorsList[indexPath.row]
return cell
}
}
如果有人有任何想法,我将不胜感激。
【问题讨论】:
-
抱歉,您能否详细说明问题所在?我对您从网络调用中获得的信息、解析数据时获得的信息以及您对这两种情况的预期感到困惑。
-
嗨!我得到的是一个项目列表,所有这些都是连续的。我想要的是每行得到一个项目。有些我的应用程序无法识别逗号,因此无法正确分隔项目。