parse.com - fatal error: unexpectedly found nil while unwrapping an Optional value. Swift -


i new in swift. question not sure how unwrapping optional value. when print object.objectforkey("profile_picture"), can see optional(<pffile: 0x7fb3fd8344d0>).

    let userquery = pfuser.query()     //first_name unique in parse. so, expect there 1 object can find.     userquery?.wherekey("first_name", equalto: currentuser)     userquery?.findobjectsinbackgroundwithblock({ (objects: [pfobject]?, error: nserror?) -> void in         if error != nil {         }         object in objects! {             if object.objectforkey("profile_picture") != nil {                 print(object.objectforkey("profile_picture"))                 self.userprofilepicture.image = uiimage(data: object.objectforkey("profile_pricture")! as! nsdata)             }         }     }) 

you'd use if let perform "optional binding", performing block if result in question not nil (and binding variable profilepicture unwrapped value in process).

it like:

userquery?.findobjectsinbackgroundwithblock { objects, error in     guard error == nil && objects != nil else {         print(error)         return     }     object in objects! {         if let profilepicture = object.objectforkey("profile_picture") as? pffile {             print(profilepicture)             {                 let data = try profilepicture.getdata()                 self.userprofilepicture.image = uiimage(data: data)             } catch let imagedataerror {                 print(imagedataerror)             }         }     } } 

or, if want data asynchronously, perhaps:

userquery?.findobjectsinbackgroundwithblock { objects, error in     guard error == nil && objects != nil else {         print(error)         return     }     object in objects! {         if let profilepicture = object.objectforkey("profile_picture") as? pffile {             profilepicture.getdatainbackgroundwithblock { data, error in                 guard data != nil && error == nil else {                     print(error)                     return                 }                 self.userprofilepicture.image = uiimage(data: data!)             }         }     } } 

it along lines, using if let unwrap optional. , have nsdata associated pffile object (from getdata method or getdatainbackgroundwithblock, presumably).

see optional binding discussion in the swift programming language.


Comments