json - Swift unexpectedly found nil after second try? -


just learning how work json on swift using apis gaming company. have encountered error in code.

fatal error: unexpectedly found nil while unwrapping optional value

though on first try in app works fine, occurs when want search name on app.

here's code have:

import uikit  class viewcontroller: uiviewcontroller {      lazy var data = nsmutabledata()      @iboutlet weak var summonername: uitextfield!      override func viewdidload() {         super.viewdidload()         // additional setup after loading view, typically nib.     }      override func didreceivememorywarning() {         super.didreceivememorywarning()         // dispose of resources can recreated.     }        func startconnection(){         var text: string = summonername.text         let urlpath: string = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/\(text)?api_key=<key>"         var url: nsurl = nsurl(string: urlpath)!         var request: nsurlrequest = nsurlrequest(url: url)         var connection: nsurlconnection = nsurlconnection(request: request, delegate: self, startimmediately: false)!         connection.start()     }      func connection(connection: nsurlconnection!, didreceivedata data: nsdata!){         self.data.appenddata(data)     }      @ibaction func buttonaction(sender: uibutton) {          startconnection()     }      func connectiondidfinishloading(connection: nsurlconnection!){         var err: nserror?         var jsonresult: nsdictionary = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.mutablecontainers, error: &err) as! nsdictionary         println(jsonresult)     } } 

edit: have added if - else jsonresult see if text entered empty or not , print method see if text inputted correctly. problem still exists on first try works fine , able extract "summonerlevel" information need, however, type name search fatal error resumed. although on search text name correctly searched for.

i think error here:

let urlpath: string = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/\(text)?api_key=<key>" var url: nsurl = nsurl(string: urlpath)! 

in urlpath should replace <key> real api key. tested code in playground, , nsurl(string: urlpath) returns nil - forced unwrapping operator applied on causes exception.

i tried changing <key> random number, , worked instead.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -