ios - How to get data from the POST json -
i creating login page once user enters username password data send api , if entered data correct returns success . if result success, need user key of user returned serverin form :
{ "status_desc": "success", "status_code": 1, "email": "keshurai1024@gmail.com", "api_token": "mqbraok1zsdasdasd4j3m" }
now need store api token. trying function not working -
@ibaction func signinbtnpressed(_ sender: any) { let email : string! = self.usernamefield.text let password : string! = self.passwordfield.text var request = urlrequest(url: url(string: "\(url_base)\(auth)\(login)")!) request.httpmethod = "post" let poststring = "email=\(email!)&&password=\(password!)" request.httpbody = poststring.data(using: .utf8) let task = urlsession.shared.datatask(with: request) { data, response, error in guard let data = data, error == nil else { // check fundamental networking error print("error=\(string(describing: error))") print("cant run") return } if let httpstatus = response as? httpurlresponse, httpstatus.statuscode != 200 { // check http errors print("statuscode should 200, \(httpstatus.statuscode)") print("response = \(string(describing: response))") print("\(email)") print("\(password)") } else { let responsestring = string(data: data, encoding: .utf8) print("responsestring = \(string(describing: responsestring))") print("\(url_base)\(auth)\(login)/?\(poststring)") alamofire.request("\(url_base)\(auth)\(login)/?\(poststring)" , method : .post).responsejson { response in let result = response.result if let dict = result.value as? dictionary<string,anyobject> { print(dict) let usertoken = dict["api_token"] as! string print(usertoken) } } } } task.resume() }
please tell me mistake m doing , how can correct ..
try parsing data json:
if let jsondata = data { { let jsonresult = try jsonserialization.jsonobject(with: jsondata, options: .allowfragments) as? [string : any] print(jsonresult) print(jsonresult?["api_token"]) //here saving aoi_token userdefaults: userdefaults.standard.setvalue(token, forkey: "api_token") print("\(userdefaults.standard.value(forkey: "api_token")!)") } catch { print("json processing failed") } }
and store api_token need use userdefaults:
userdefaults.standard.setvalue(token, forkey: "api_token") print("\(userdefaults.standard.value(forkey: "api_token")!)")
Comments
Post a Comment