I'm an beginner with Swift and Xcode and I'm trying to fetch API data from TMDb API and display it in a UITableView
.
I get the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The highlighted line is:
self.nyheterTableView.reloadData()
And my complete code for the viewController is:
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
}
}
Complete code for APIController is:
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)
}
})
}
}
I belive the problem occurs at the reloadData()
since before reload the row count is 20 and later on when returned at the function it's 00. Alternatively it occurs in the APIController which is don't quite fully understand.
I've been following the following guide: http://www.sitepoint.com/introduction-swift-programming-language/ (About 3/4 down the page)
As said, i'm a beginner at Swift, Xcode and native iOS programming, help greatly appreciated.
Cheers.