when we need to call any request to the network we most probably use delegate methods to send data and get a response when you only need to call a single function we will create for them an interface (Protocol in swift) which is not a good programming practice. So if you need to call a single you must use the callbacks in swift if you need to implement more than one function and also want that these all functions are to be implemented in your class you can use delegates. Here is the steps to create the callback in swift:-
1 2 3 4 5 |
import Foundation class NetworkManager: NSObject { } |
1 2 3 |
func fetchData(params : String , _ completion: @escaping ServiceResponse) -> Void { } |
1 2 3 4 5 |
typealias ServiceResponse = (JSON?, Error?) -> Void //JSON it is Swifty json object you can use Any or AnyObject or NSdictionary or Dictionary in which format you need the data // Error will if your request contains an error |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
func fetchData(params : String , _ completion: @escaping ServiceResponse) -> Void { var baseURLWithAPIKeyString = "\(self.baseURLString)\(params)/" let requestURL: String = baseURLWithAPIKeyString print(requestURL) var request1 = URLRequest(url: URL(string : requestURL)!) request1.httpMethod = "GET" request1.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData let encodedData = GlobalData.Credentials.BASEDATA.data(using: String.Encoding.utf8)! let base64String = encodedData.base64EncodedString() request1.addValue("application/json", forHTTPHeaderField: "Content-Type") request1.addValue("application/json", forHTTPHeaderField: "Accept") request1.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization") Alamofire.request(request1).responseJSON { (response) in switch response.result { case .success: let jsonData = JSON.init(data: response.data!) completion(jsonData , nil) case .failure(let error): completion( nil , error as NSError) } } } |
1 2 3 4 5 6 7 8 9 |
var params = "Youur parameters" let networkManager = NetworkManager() networkManager.fetchData(params: params) { (responseObject:JSON?, error:Error?) in if (error != nil) { print("Error logging you in!") } else { print("Do something in the view controller in response to successful login!",responseObject! ) } } |
Be the first to comment.