我正在开发一个应用程序,可以从 Facebook 下载姓名和图像,并将它们显示到 CollectionView 中。图片功能运行得很好,但有一个小细节我对名称感到困惑。这是文本的 CollectionView 函数内的代码:
let url = NSURL(string: "http://www.facebook.com/" + newArray[indexPath.row])!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
let websiteArray = webContent!.componentsSeparatedByString("pageTitle\">")
let secondArray = websiteArray[1].componentsSeparatedByString("</title>")
let title = secondArray[0]
//----- serperated ---------
dispatch_async(dispatch_get_main_queue())
{
if title == "Page Not Found" || title == "Pagina Niet Gevonden" {
} else {
stalkers.append(title)
}
}
}
}
task.resume()
cell.label.text = stalkers[indexPath.row]
return cell
问题是当应用程序启动时,它会崩溃并出现错误“数组超出索引”。我认为这是因为加载时数组为空,并且下载需要一段时间。我不知道如何让标签在下载后显示每个名称。
非常感谢任何帮助,真的!谢谢!
最佳答案
首先检查一下:
if stalkers.count >= indexPath.row {
cell.label.text = stalkers[indexPath.row]
}
下载后,指定标题:
dispatch_async(dispatch_get_main_queue())
{
if title == "Page Not Found" || title == "Pagina Niet Gevonden" {
} else {
stalkers.append(title)
}
cell.label.text = stalkers[indexPath.row] //Add this line after download done.
}
关于ios - 由于下载延迟,数组超出索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668844/