iosswiftfatal-errornsurloptional-values

Swift 2.0 fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)


let imgURL:NSURL = NSURL(string: "\(ImageName)")!

at the above line,i'm getting fatal error

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Code :

let ImageName = obj["image"] as! String

 let imgURL:NSURL = NSURL(string: "\(ImageName)")!
 let request: NSURLRequest = NSURLRequest(URL: imgURL)

  let session = NSURLSession.sharedSession()

  let Imgtask = session.dataTaskWithRequest(request){
                            (data, response, error) -> Void in

   if (error == nil && data != nil)
    {
       func display_image()
       {
           pointAnnoation.DisplayImage = UIImage(data: data!)
        }
        dispatch_async(dispatch_get_main_queue(), display_image)
     }

   }

   Imgtask.resume()

From the above code im trying to store my image from database in annotation

if i printed the 'ImageName' it returns the name from the database correctly, but unable to retain the image

it resulting in the error while running.


Solution

  • Try to use guard or if let for helping yourself.

    let ImageName = obj["image"] as! String
    
     if let imgURL = NSURL(string: ImageName) {
         let request: NSURLRequest = NSURLRequest(URL: imgURL)
    
         let session = NSURLSession.sharedSession()
    
         let Imgtask = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
    
            if (error == nil && data != nil)
            {
                // What's that func??
                func display_image()
                {
                    pointAnnoation.DisplayImage = UIImage(data: data!)
                }
                dispatch_async(dispatch_get_main_queue(), display_image)
             }
    
           }
     }
     Imgtask.resume()