Unexpectedly found nil while unwrapping an Optional value» Error
on line
let test: Element? = try doc!.select("div.image").first()!
I want to get the all the elements inside between div with class image using SwiftSoup while passing different url link .If there is no div with class image Then I want to print "Error"
I have Optional binding with if let ... but also it get error..
How to safely check optional value?
import UIKit
import WebKit
import SwiftSoup
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let session = URLSession.shared
let url = URL(string: "http://www.example.com.html")!
let task = session.dataTask(with: url ) { (data, response, error) in
// Check whether data is not nil
guard let loadedData = data
else {
return
}
// Load HTML code as string
let contents = String(data: loadedData, encoding: .utf8)
do {
let html: String? = contents
let doc: Document? = try SwiftSoup.parse(html!)
let test: Element? = try doc!.select("div.image").first()!
if let test1 = test{
print(test1)
}else {
print("error")
}
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
}
task.resume()
}
}