I am trying to open a link inside app, but when I click the cell (didSelectRowAt), I get an error (Fatal error: Unexpectedly found nil while unwrapping an Optional value: file). If I change (titleLink = "he is the link"), it works. What should I change to get not an error?
The error is in didSelectRowAt, you can see it as a comment.
import UIKit
import SafariServices
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, XMLParserDelegate {
@IBOutlet weak var tableView: UITableView!
var parser = XMLParser()
var post = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var textLink = NSMutableString()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
parsingDataFromUrl()
}
func parsingDataFromUrl() {
post = []
parser = XMLParser(contentsOf: NSURL(string: "feedRssLinkHere")! as URL)!
parser.delegate = self
parser.parse()
tableView.reloadData()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
element = elementName as NSString
if (elementName as NSString).isEqual(to: "item") {
elements = NSMutableDictionary()
elements = [:]
title1 = NSMutableString()
title1 = ""
textLink = NSMutableString()
textLink = ""
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if element.isEqual(to: "title") {
title1.append(string)
} else if element.isEqual(to: "link") {
textLink.append(string)
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if (elementName as NSString).isEqual(to: "item") {
if !title1.isEqual(nil) {
elements.setObject(title1, forKey: "title" as NSCopying)
}
if !textLink.isEqual(nil) {
elements.setObject(textLink, forKey: "link" as NSCopying)
}
post.add(elements)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return post.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MainCell
if cell.isEqual(NSNull()) {
cell = Bundle.main.loadNibNamed("Cell", owner: self, options: nil)! [0] as! MainCell
}
cell.titleLabel.text = (post.object(at: indexPath.row) as AnyObject).value(forKey: "title") as! NSString as String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let titleLink = (post.object(at: indexPath.row) as AnyObject).value(forKey: "link") as! NSString as String
let svc = SFSafariViewController(url: URL(string: titleLink)!) // Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
present(svc, animated: true, completion: nil)
}
}