我是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