-4

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()
    }

}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 3
    Possible duplicate of: [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – TylerP Apr 24 '20 at 06:42

1 Answers1

1

Replace your code with this:

let session = URLSession.shared guard let url = URL(string: "http://www.example.com.html") else {return}

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 {
                    guard let html: String = contents else {return}
                    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()

  }
Zain
  • 153
  • 9