我是Swift和Xcode的初学者,我试图从获取TMDb API的API数据并将其显示在UITableView
中。 我收到以下错误:reloadData()使用Swift
fatal error: unexpectedly found nil while unwrapping an Optional value
的亮的行是:
self.nyheterTableView.reloadData()
而且我对的viewController完整的代码是:
import UIKit
class nyheterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {
@IBOutlet weak var nyheterTableView: UITableView!
var searchResultsData: NSArray = []
var api: APIController = APIController()
func JSONAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.searchResultsData = results
print(self.searchResultsData.count) // <- 20
self.nyheterTableView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
//Construct the API URL that you want to call
var APIkey: String = "The deeper thought is, the taller it becomes." //Replace with your Api Key"
var APIBaseUrl: String = "http://api.themoviedb.org/3/movie/upcoming?api_key="
var urlString:String = "\(APIBaseUrl)" + "\(APIkey)"
//Call the API by using the delegate and passing the API url
self.api.delegate = self
api.GetAPIResultsAsync(urlString)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(self.searchResultsData.count) // <- 00
return searchResultsData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier: String = "nyheterResultsCell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
//Create a variable that will contain the result data array item for each row
var cellData: NSDictionary = self.searchResultsData[indexPath.row] as NSDictionary
//Assign and display the Title field
cell.textLabel?.text = cellData["original_title"] as? String
// Get the release date string for display in the subtitle
var releaseDate: String = cellData["release_date"] as String
cell.detailTextLabel?.text = releaseDate
return cell
}
}
为APIController完整代码:
import UIKit
protocol APIControllerProtocol {
func JSONAPIResults(results: NSArray)
}
class APIController: NSObject {
var delegate:APIControllerProtocol?
func GetAPIResultsAsync(urlString:String) {
//The Url that will be called
var url = NSURL.URLWithString(urlString)
//Create a request
var request: NSURLRequest = NSURLRequest(URL: url)
//Create a queue to hold the call
var queue: NSOperationQueue = NSOperationQueue()
// Sending Asynchronous request using NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
//Serialize the JSON result into a dictionary
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
//If there is a result add the data into an array
if jsonResult.count>0 && jsonResult["results"]?.count > 0 {
var results: NSArray = jsonResult["results"] as NSArray
//Use the completion handler to pass the results
self.delegate?.JSONAPIResults(results)
} else {
println(error)
}
})
}
}
我相信问题发生在reloadData()
,因为在重新加载行计数为20和以后时,它返回的函数是00.或者它发生在APIController中,它不完全理解。 我一直在关注以下指南:http://www.sitepoint.com/introduction-swift-programming-language/(向下3/4页)
如上所述,我是Swift初学者,Xcode和原生iOS编程,非常感谢。
干杯。
-1因为在重新加载应用程序崩溃期间,所有插座都正确连接。 – Ramesh 2014-09-19 11:17:16
我不同意。我可能会误解,但我相信当OP调用'reloadData()'时,应用程序崩溃,*因为*表视图是'nil'。我不认为他实际上看到了行,他提到的值“20”是在他第一次尝试重新加载表之前从控制台“print()”中。所以他*在他的HTTP请求中有* 20个值,但是在后端提取和填充表之间失败。 – 2014-09-19 11:25:47
你绝对正确,克雷格。 – 2014-09-19 11:28:45