şö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)")
}
}
}