Search code examples
swiftwcsession

Fatal error: swift 2.3 when unwrapping value


I'm trying to send a saved string to the apple watch with WCsession methode. But when I do this I get an error in swift 2.3: fatal error: unexpectedly found nil while unwrapping an optional value !!

func Reloadip() {


    let ip =  nsdefauts.object(forKey: saved)


    let requestValues = ["send" : "A" , "IP" : ip as! String ]
    print(requestValues)

    if(WCSession.isSupported()){
        session!.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
        print("sended ip")
    }

}

the error is made at the "ip as! String line" how can I fix this. ?

regards Quinn


Solution

  • You should use more safe code instead

    func Reloadip() {
    
        guard let ip = nsdefauts.objectForKey(saved) as? String else {
            print("there is no saved ip")
            return
        }
    
        let requestValues = ["send" : "A" , "IP" : ip]
        print(requestValues)
    
        if(WCSession.isSupported()){
            session?.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
            print("sended ip")
        }  
    }