Skip to main content

Swift API Manager -Alamofire-Refresh Token-With TestCases

  import Foundation import KeychainAccess enum APIError : Error { case accessTokenExpired case networkError // Add more error cases as needed } class APIManager { private let keychain = Keychain (service: "com.example.app.refreshToken" ) private let refreshTokenKey = "refreshToken" private var accessToken: String ? func callAPI < T : Codable >( urlString : String , method : String , parameters : [ String : Any ] ? , completion : @escaping ( Result < T , APIError >) -> Void ) { guard let url = URL (string: urlString) else { completion(.failure(.networkError)) return } var request = URLRequest (url: url) request.httpMethod = method // Add access token to the request headers if available if let token = accessToken { request.setValue( "Bearer \(token) " , forHTTPHeaderField: "Aut...

One Line JSON Parsing Swift 4 Simple Example


 One Line Parsing JSON in Swift 4.0 With Codable or Decodle

 Swift 4 includes a new way to generate and parse JSON with Swift Codable protocol.


 JSON:-
{
"name" = Rahul'
"id" = 10
"collage" = RTS Collage
"code" = A190
}
 Start:-
 import UIKit
struct  Profile: Codable {
let name: String
let id: Int
let  collage: String
let code: String

 Convert Item(Profile) to JSON
 init?(json: [String: Any]){
 guard let name = json["name" ] as?  String,
           let id= json["id" ] as?  Int,
           let collage= json["collage"  ]as?  String,
           let code= json["code" ] as?  String, else { return nil}
 self.name = name
self.id = id
self.collage = collage
self.code = code
}
}
class ViewController: UIViewController {
  guard let url = URL(string: "https://xxxxxxxxxx") else {return}
  URLSession.shared.dataTask(with: url) { (data, response  , error) in   
   guard let data = data else {return}
    do{
           let decoder = try JSONDecoder().decoder(Profile.self, from: data)
 // check access data......
         print(decoder.name)         
     } catch let err{
        print("Err", err)
     }
   }.resume()
}


Comments