【发布时间】:2015-11-30 16:10:24
【问题描述】:
我需要以下代码方面的帮助。由于某种原因,歌曲列表没有显示在表格中。从我的角度来看,一切都很好。如果有人能看到明显的东西,请指出。这是我的快速代码:
func getMusicFilesInDirectory() -> [String] {
// get the documents folder url
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
// get the directory contents (including folders)
do {
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
print(directoryContents)
} catch let error as NSError {
print(error.localizedDescription)
}
// filter the directory to extract only Wav Files
do {
let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
print(directoryUrls)
let wavFilesDir = directoryUrls.filter(){ $0.pathExtension! == "wav" }.map{ $0.lastPathComponent! }
wavFiles = ["Music Files:\n" + wavFilesDir.description]
} catch let error as NSError {
print(error.localizedDescription)
}
return wavFiles
}
// table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return wavFiles.count;
return getMusicFilesInDirectory().count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = getMusicFilesInDirectory()[indexPath.row]
cell.textLabel?.text = wavFiles[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell#\(indexPath.row)")}
在听从下面这些人的一些线索后,我修改了代码并添加了以下方法。目前我仍然没有让列表显示在我的表中,原因是音乐文件无法在存储的目录中访问。一旦他们被移动到文档目录,一切都应该得到解决。完成后我会发布另一个更新。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
getFileCount({(success: Bool, error: String)-> Void in
if success{
tableView.reloadData();
} else {
print("No wave files Found");
}
})
//print("You selected cell#\(indexPath.row)")
}
func getFileCount (completionHandler : (success: Bool, error: String) -> Void) -> [String] {
if wavFiles.count > 0 {
completionHandler(success: true, error: "none");
}else {
completionHandler(success: false, error: "No files found");
}
return wavFiles
}
【问题讨论】:
-
你在哪里
reloadDatatableview?也许你忘了? -
我认为拥有完成处理程序将是一种有用的方式,因为您不会在加载数据后重新加载数据。只是一个建议:最好存储 getMusicFilesInDirectory 的结果,每次填充单元格时调用该函数。
-
@Eric D, @ kaizoku, 非常好的建议。试图找出在哪里重新加载数据。
-
好的,你可以在函数定义中创建一个completionHandler。在变量上调用此函数时,定义完成处理程序的主体,您可以在那里编写 reloadData。所以一旦整个数据集被加载,你的 tableView.reloadData 就会被调用
标签: ios swift uitableview audio-player