Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- login(json: json) {status, token, code in
- if(token != nil && code == 200){
- print(token)
- }
- else{
- print(1)
- print(token)
- print(code)
- }
- }
- func login(json:Any,completionHandler: (_ granted: Bool, _ token: String?, _ code: Int?) -> ()){
- var codeToSend:Int = 0
- var token:String = ""
- POST(json: json){ data, code in
- if(code == 200)
- {
- do{
- if let json_response = try JSONSerialization.jsonObject(with: data, options: [])as? [String:Any]{
- if let temp_token = json_response["auth_token"]{
- print(temp_token as! String)
- token = temp_token as! String
- codeToSend = 200
- }
- }
- else{
- print("неизвестная ошибка")
- }
- }
- catch{
- print("errasd")
- print(error)
- }
- }
- else if(code == 400)
- {
- token = ""
- codeToSend = 400
- print("Неверное имя пользователя или пароль")
- }
- else{
- token = ""
- codeToSend = 0
- }
- }
- // return (token, codeToSend)
- completionHandler(true, token,codeToSend)
- }
- func POST(json: Any, callback: @escaping (_ data: Data, _ code: Int?) -> ())
- {
- guard let url = URL(string: ngrok+"/api/auth/token/create")else{return}
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- request.setValue("application/json", forHTTPHeaderField:"Content-Type")
- guard let httpBody = try? JSONSerialization.data(withJSONObject: json, options: [])else {return}
- request.httpBody = httpBody
- let sessionConfig = URLSessionConfiguration.default
- sessionConfig.timeoutIntervalForRequest = 5.0
- sessionConfig.timeoutIntervalForResource = 60.0
- URLSession(configuration: sessionConfig).dataTask(with: request){(data, response, error) in
- if error != nil{
- print("Ошибка севреа")
- DispatchQueue.main.async {callback(Data("".utf8), 0)}
- }
- if let response = response{
- print(response)
- if let httpResponse = response as? HTTPURLResponse{
- DispatchQueue.main.async {callback(
- data!, httpResponse.statusCode)
- }
- }
- }
- }.resume()
- }
Advertisement
Add Comment
Please, Sign In to add comment