Hoşgeldin. Soru sormak veya cevaplamak için hemen üye ol.
0 oy
471 kez görüntülendi
ios development kategorisinde tarafından

Merhabalar herkese,

kullanıcı girişi yapmak icin web servise post islemi gerçekleştiriyorum, butona tıklayıp kullanıcı adi ve parolayı post ediyorum doğru ise;

{
"accesstoken" = "bZj8O-i-J6Kj5Hm12spnQ4EFN9RnlU2ZEeDYXe6aGU33qFIyxTG0AIWk8KPKRy-eqC4N-6z2yXlhh9pOb0Fdv-bcjy9-FVJemKVZRsbTCfTxXmVjfFXbbWd9mMJ5uBVl8DH4T-O4cL2sbk3wlDZpwb12ynUB7408pYlNpuqTJ4FBsK5UrXHJsx4aQLadtZV7lKNILYlvs2okU60bxAdAtA2f1tWCYyEIsYpk";
"expiresin" = 35999;
"token
type" = bearer; }

yanlis ise ;

{
error = "Ge\U00e7ersiz istek";
"error_description" = "Hatal\U0131 kullan\U0131c\U0131 bilgisi..."; }

terminal çıktılarını alıyorum. Ancak gelen degerlere göre doğru login action'nunu gercekleştiremedim. json'dan böyle parse etmeyi denedim ancak bunu bir sabite atayamadım login prosedürünü düzenleyemedim.

if let succesful = json["token_type"] as AnyObject? {
//datayi burada bir sabite append edemedim.
print(succesful)
}

fonksiyonum bu şekilde;

func LoginProcess(username:String,password:String){
    
    let url = NSURL(string: "http://api.xxxxx.com/token")
    
    let request = NSMutableURLRequest(url: url! as URL)
    
    request.httpMethod = "POST"
    
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    
    let post = "username=\(username)&password=\(password)&grant_type=password"
    
    request.httpBody = post.data(using: String.Encoding.utf8)
    
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        
        
        if let mydata = data {
            do {
                let json = try JSONSerialization.jsonObject(with: mydata, options: []) as AnyObject 
                
                print(json)

            } catch {
                print(error)
            }
        }
        
    }
    
    task.resume()
    
}

bilgisi olan arkadaşlar yardımcı olursa sevinirim nasıl bir yapı kurmalıyım acaba?

Herkese iyi çalışmalar.

1 cevap

0 oy
tarafından
tarafından seçilmiş
 
En İyi Cevap

şöyle bişeyler olarabilir mesela

class LoginProcess {
    class func letLoginWith(userName: String, password: String, completion:@escaping([String:Any]?, Error? ) -> Void) {
        let urlString:String = "http://api.xxxxx.com/token"
        if let url = URL(string: urlString) {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            let postData = "username=\(userName)&password=\(password)&grant_type=password"
            request.httpBody = postData.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
                if error == nil {
                    if let receivedData = data {
                        do {
                            let json = try JSONSerialization.jsonObject(with: receivedData, options: [])
                            if let dict = json as? [String:Any] {
                                completion(dict, nil)
                            } else {
                                completion(nil, nil)
                            }
                        } catch let JSONSerializationError {
                            completion(nil, JSONSerializationError)
                        }
                    } else {
                        completion(nil, nil)
                    }
                } else {
                    completion(nil, error)
                }
            })
            task.resume()

        } else {
            completion(nil, nil)
        }
    }
}

şöyle kullanırsın;

override func viewDidLoad() {
        super.viewDidLoad()

        LoginProcess.letLoginWith(userName: "deneme", password: "1234568") { (response, error) in
            if let receivedResponse = response {
                if let accesstoken = receivedResponse["accesstoken"] as? String {
                    if let expiresin = receivedResponse["expiresin"] as? Int {
                        if let tokentype = receivedResponse["tokentype"] as? String {
                            print("accesstoken:\(accesstoken) expiresin:\(expiresin) tokentype:\(tokentype)")
                        }
                    }
                } else if let error = receivedResponse["error"] as? String {
                    if let error_description = receivedResponse["error_description"] as? String {
                        print("error:\(error) error_description:\(error_description)")
                    }
                }
            }
            if let receivedError = error {
                print("error:\(receivedError.localizedDescription)")
            }
        }
    }
tarafından

cevabını için teşekkür ederim Yasin hocam, dün json'ı parse edip, doğru değerlerin girildiği senaryoda "toke_type" ı yanlış ise "error"u birer string'e atayıp, gerekli parametrelerle login işlemini gerçekleştirebildim. Sizin cevabınızdaki kodlarla da işlem yapabildim. Tekrar teşekkür ederim. :)

...