i've log in page in app in i'm doing authentication , making post request. i'll grabbing token api i'm provided with. however, code isn't printing on print log. please help!!
@ibaction func submit(sender: anyobject) { //creating function connect api func connecttowebapi(){ //setting base64-encoded credentials let username = "user" let password = "pass" let loginstring = nsstring(format: "%@:%@", username, password) let logindata: nsdata = loginstring.datausingencoding(nsutf8stringencoding)! let base64loginstring = logindata.base64encodedstringwithoptions(nil) //creating request let url = nsurl(string: "http://www.telize.com/geoip") var request = nsmutableurlrequest(url: url!) let config = nsurlsessionconfiguration.defaultsessionconfiguration() let session = nsurlsession.sharedsession() request.addvalue("application/json", forhttpheaderfield: "content-type") request.addvalue("application/json", forhttpheaderfield: "accept") let urlconnection = nsurlconnection(request: request, delegate: self) request.httpmethod = "post" request.setvalue(base64loginstring, forhttpheaderfield: "authorization") let task = session.datataskwithurl(url!, completionhandler: {data, response, error -> void in if (error != nil) { println(error) } else { // converting data dictionary let jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.mutablecontainers, error: nil) as! nsdictionary println(jsonresult) } }) //fire off request task.resume() }
a couple of issues:
first, you're using both
nsurlconnection,nsurlsession. means you're performing request twice. nowadays,nsurlconnectionbeing deprecated soon, should eliminatensurlconnectionportion of code snippet , usensurlsession.second, when parsing json, you've explicitly told not report error (you set
errorparameternil). should @ error, if any:var parseerror: nserror? if let jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.mutablecontainers, error: &parseerror) as? nsdictionary { println("jsonresult = \(jsonresult)") } else { // if didn't work, show enough can figure out why: println("parseerror = \(parseerror)") println("response = \(response)") let responsestring = nsstring(data: data, encoding: nsutf8stringencoding) println("responsestring = \(responsestring)") // html server describing problem in request }
usually these sorts of requests fail because of wrong how original nsurlrequest created, not showing enough information source of problem.
Comments
Post a Comment