How to use singleton with Alamofire using Swift 3? - ios

I am new in iOS and I am bit confused that how to use singleton with Alamofire and how singleton is important. I created a networkWrapper class in that I have written Alamofire post and get method, but I didn't use singleton.
How can I create a Wrapper class of Alamofire with singleton? How can I get all tricks that is really important?
Below is my code for wrapper class:
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class AFWrapper: NSObject {
//TODO :-
/* Handle Time out request alamofire */
class func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void)
{
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
//let title = resJson["title"].string
//print(title!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
static func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
In my controller:
if newLength == 6
{
let textZipCode = textField.text! + string
let dict = ["id" : "43","token": "2y103pfjNHbDewLl9OaAivWhvMUp4cWRXIpa399","zipcode" : textZipCode] as [String : Any]
//Call Service
AFWrapper.requestPOSTURL(HttpsUrl.Address, params: dict as [String : AnyObject]?, headers: nil, success: { (json) in
// success code
print(json)
}, failure: { (error) in
//error code
print(error)
})
setFields(city: "Ajmer", state: "Rajasthan", country: "India")
return newLength <= 6
}

I didn't look deep into your code. In swift we can create singleton by
static let sharedInstance = AFWrapper()
And it will create singleton instance of a class, so that class and static for singleton class instance functions are not necessary. Please refer below code for singleton class.
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class AFWrapper: NSObject {
static let sharedInstance = AFWrapper()
//TODO :-
/* Handle Time out request alamofire */
func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void)
{
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
//let title = resJson["title"].string
//print(title!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
Now you can call Singleton class instance function by
AFWrapper.sharedInstance.requestPOSTURL(HttpsUrl.Address, params: dict as [String : AnyObject]?, headers: nil, success: { (json) in
// success code
print(json)
}, failure: { (error) in
//error code
print(error)
})

May be you need that :
import UIKit
import Alamofire
struct FV_API
{
//URL is http://www.stack.com/index.php/signup
static let appBaseURL = "" // assign your base url suppose: http://www.stack.com/index.php
static let apiSignUP = "" // assign signup i.e: signup
}
class APIManager: NSObject
{
//MARK:- POST APIs
class func postAPI(_ apiURl:String, parameters:NSDictionary, completionHandler: #escaping (_ Result:AnyObject?, _ Error:NSError?) -> Void)
{
var strURL:String = FV_API.appBaseURL // it gives http://www.stack.com/index.php and apiURl is apiSignUP
if((apiURl as NSString).length > 0)
{
strURL = strURL + "/" + apiURl // this gives again http://www.stack.com/index.php/signup
}
_ = ["Content-Type": "application/x-www-form-urlencoded"]
print("URL -\(strURL),parameters - \(parameters)")
let api = Alamofire.request(strURL,method: .post, parameters: parameters as? [String : AnyObject], encoding: URLEncoding.default)
// ParameterEncoding.URL
api.responseJSON
{
response -> Void in
print(response)
if let JSON = response.result.value
{
print("JSON: \(JSON)")
completionHandler(JSON as AnyObject?, nil)
}
else if let ERROR = response.result.error
{
print("Error: \(ERROR)")
completionHandler(nil, ERROR as NSError?)
}
else
{
completionHandler(nil, NSError(domain: "error", code: 117, userInfo: nil))
}
}
}
In other NSObject I made that method i.e for Signup:
class SignUp: NSObject
{
class func registerWithAPI(firstName: String, lastName:String, completionHandler: #escaping (_ Result:AnyObject?, _ Error:NSError?) -> Void)
{
let dict = NSMutableDictionary()
if !firstName.isEmpty
{
dict.setValue(firstName, forKey: "firstname")
}
if !lastName.isEmpty
{
dict.setValue(lastName, forKey: "lastname")
}
APIManager.postAPI(FV_API.apiSignUP, parameters: dict)
{
(Result, Error) -> Void in
completionHandler(Result, Error)
}
}
}
In controller class I made method to call api like:
func apiForSignup()
{
SignUp.registerWithAPI(firstName: txtFieldFirstName.text!, lastName: txtFieldLastName.text!)
{
(Result, Error) -> Void in
// write code
}

Updated for Swift 4
import UIKit
import Alamofire
import SwiftyJSON
//
// MARK:- ipv6 Configuration...
//
private var webView = UIWebView(frame: CGRect.zero)
private var secretAgent: String? = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")
var authHeaders: HTTPHeaders = ["User-Agent": secretAgent!, "Content-Type": "application/json; charset=utf-8"]
class ApiManager: NSObject {
static let sharedInstance = ApiManager()
func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void) {
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess, let resJson = responseObject.result.value {
success(JSON(resJson))
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
func requestPOSTURL(_ strURL: String, params: [String : Any]?, headers: [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void) {
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: authHeaders).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess, let resJson = responseObject.result.value {
success(JSON(resJson))
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}

Related

iOS swift How to call Alamofire with call back to get the data in Viewcontroller

I am using Alamofire [pod 'Alamofire', '~> 5.0.0-rc.3'] in my project and AFWrapper created in wrapper class for Alamofire functions how to use completion handlers to get the data in view controllers.
this is AFWrapper class code
class AFWrapper
{
This is my post request code
func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
let dic = ["NSLocalizedDescription" : error.localizedDescription]
failure(error)
}
}
}
This is my get request code
func requestGetWithParamsURL(_ strURL : String, headers : [String : String]?, params : [String : AnyObject]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
let dic = ["NSLocalizedDescription" : error.localizedDescription]
failure(error)
}
}
}
}

How to add ssl certificate pinning in ios app swift4 using alamofire manager?

I have problem on ssl certificate pinning in my ios app, what I want is add ssl pinning certificate to all requests using alamofire, so below is my code of the alamofire manager, when I run the app I always get this error:
load failed with error Error Domain=NSURLErrorDomain Code=-999
"cancelled"
UserInfo={NSErrorFailingURLStringKey=https://myWebsite.com/token,
NSErrorFailingURLKey=https://myWebsite.com/token,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask .<1>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>,
NSLocalizedDescription=cancelled} [-999]
class AFManager : NSObject{
private var sessionManager: SessionManager?
required override init() {
super.init()
enableCertificatePinning()
}
private func enableCertificatePinning() {
let certificates = getCertificates()
let trustPolicy = ServerTrustPolicy.pinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true)
let trustPolicies = [ "myWebsite.com": trustPolicy ]
let policyManager = ServerTrustPolicyManager(policies: trustPolicies)
sessionManager = SessionManager(
configuration: .default,
serverTrustPolicyManager: policyManager)
}
private func getCertificates() -> [SecCertificate] {
let url = Bundle.main.url(forResource: "myWebsitessl", withExtension: "cer")!
let localCertificate = try! Data(contentsOf: url) as CFData
guard let certificate = SecCertificateCreateWithData(nil, localCertificate)
else { return [] }
return [certificate]
}
///without headers (post)
//used this to registration
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
self.init().sessionManager?.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
///// response string (post)
//used this in login // used in change password
class func strRequestPOSTURL(_ strURL : String, params : [String : String]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
self.init().sessionManager?.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response) in
//print(response)
if response.result.isSuccess {
let resJson = JSON(response.result.value!)
success(resJson)
}
if response.result.isFailure {
let error : Error = response.result.error!
failure(error)
}
}
}
}
My code was like this, see code below, and it was working, but I want certificate pinning for security so I add the things(Like sessionManager, init(),enableCertificatePinning() and getCertificates()) in the above code and after that its not working
class AFManager : NSObject{
///without headers (post)
//used this to registration
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
Alamofire.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
///// response string (post)
//used this in login // used in change password
class func strRequestPOSTURL(_ strURL : String, params : [String : String]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
URLCache.shared.removeAllCachedResponses()
Alamofire.request(strURL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response) in
//print(response)
if response.result.isSuccess {
let resJson = JSON(response.result.value!)
success(resJson)
}
if response.result.isFailure {
let error : Error = response.result.error!
failure(error)
}
}
}
}
I added the certificate to my project by drag and drop it inside the project, please help, I feel my code has some mistakes
thanks in advance
Error -999 is most commonly seen when your SessionManager is deinit'd while being used, causing all of your requests to be cancelled. From your code its looks like you're not using the sessionManager variable you've created with your custom ServerTrustPolicy at all and even if you were it's likely that whatever instance of AFManager you've created is going out of scope, causing the deinit.
You may use sessionManager, I use this class below, it creates array of certificates from your bundle;
class NetworkManager
{
static let sharedInstance = NetworkManager()
var manager: SessionManager?
init()
{
var certificates = ServerTrustPolicy.certificates(in: Bundle.main)
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"yourUrl.com": .pinCertificates(
certificates: ServerTrustPolicy.certificates(in: Bundle.main),
validateCertificateChain: true,
validateHost: true
)
]
manager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
}
}
Then I do request like that,
//request depends on your needs. Post, get etc..
var request = URLRequest(url: yourUrl)
request.httpMethod = HTTPMethod.get.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
networkManager.manager!.request(request).responseJSON
By the way don't forget to create your networkManager object
var networkManager = NetworkManager.sharedInstance

Swift: passing values from different scopes in closures

Evening, I'm fetching the data from an API, and I'm having problems to passing the masons through different scopes:
I have this fun in my controller:
func getDaily() {
let json = NetworkManager.getDaily()
print(json)
}
And this one in a NetworkManager Class
class func getDaily() -> JSON {
//Setting the url for the request
let url = "\(base_url)planetary/apod?api_key=\(apy_key)"
var json: JSON = []
//Making the request
Alamofire.request(url, method: .get).validate().responseJSON{ response in
switch response.result {
case .success(let value):
json = JSON(value)
//print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
return json
}
and obviously the json printing in the first func is always empty.
Can you please explain me the way to do this?
Your function getDaily() should not be returning JSON. Because this is an async request you need a callback. Try it like this:
class func getDaily(result: #escaping (JSON) -> ()) {
//Setting the url for the request
let url = "\(base_url)planetary/apod?api_key=\(apy_key)"
var json: JSON = []
//Making the request
Alamofire.request(url, method: .get).validate().responseJSON{ response in
switch response.result {
case .success(let value):
json = JSON(value)
result(json)
case .failure(let error):
print(error)
}
}
}
Your caller would then become:
func getDaily() {
NetworkManager.getDaily { json in
print(json)
}
}
For me this is the correct way:
import UIKit
import Alamofire
class APIManager: NSObject {
static let sharedInstance = APIManager()
//TODO :-
/* Handle Time out request alamofire */
func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void)
{
Alamofire.request(strURL).responseJSON { (responseObject) -> Void in
//print(responseObject)
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
//let title = resJson["title"].string
//print(title!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
/********************************* To get response in another class ********************************/
APIManager.sharedInstance.requestPOSTURL(HttpsUrl.Address, params: dict as [String : AnyObject]?, headers: nil, success: { (json) in
// success code
print(json)
}, failure: { (error) in
//error code
print(error)
})

Alamofire timeout not working

In my app I am using Alamofire for network request and I created a class. Here is the class
class MGNetworking: NSObject{
private class func getAlamofireManager() -> SessionManager {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 180 // seconds
configuration.timeoutIntervalForRequest = 180 // seconds
let alamofireManager = Alamofire.SessionManager(configuration: configuration)
return alamofireManager
}
class func requestGETURL(_ strURL: String, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void) {
getAlamofireManager().request(strURL,method: .get).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
class func requestPOSTURL(_ strURL : String, params : [String : AnyObject]?, headers : [String : String]?, success:#escaping (JSON) -> Void, failure:#escaping (Error) -> Void){
getAlamofireManager().request(strURL, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
success(resJson)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}
}
}
I want change timeout for my network request. I created method getAlamofireManager() but when I am calling this method my request cancelled here is the error.
FAILURE: Error Domain=NSURLErrorDomain Code=-999 "cancelled"
When I change getAlamofireManager() to Alamofire.request it is start working perfect.
I can make an assumption that issue is connected with this reported problem.
So lets rewrite code:
class MGNetworking: NSObject{
var manager: SessionManager?
init() {
manager = getAlamofireManager()
}
private class func getAlamofireManager() -> SessionManager {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 180 // seconds
configuration.timeoutIntervalForRequest = 180 // seconds
let alamofireManager = Alamofire.SessionManager(configuration: configuration)
return alamofireManager
}
}
So now use manager instead of the getAlamofireManager() for the requests

Swift: Handling JSON with Alamofire & SwiftyJSON

This is sure to be asked several times, but I have not yet found the right answer, although I have been looking very hard.
I use Alamofire and SwiftyJSON and my JSON data looks like that:
{
"528" : {
"name" : "Name 1",
"id" : "528",
"product_id" : null,
"visible" : "0",
"level" : "2"
},
"29" : {
"name" : "Name 2",
"id" : "29",
"product_id" : null,
"visible" : "1",
"level" : "1"
},
"173" : {
"name" : "Name 3",
"id" : "173",
"product_id" : null,
"visible" : "0",
"level" : "2"
},
"143" : {
"name" : "Name 4",
"id" : "143",
"product_id" : null,
"visible" : "1",
"level" : "2"
},
...with this code:
Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)
.responseJSON { (request, response, jsonData, error) in
let json = JSON(jsonData!)
println(json)
}
...so everything should be fine with JSON
How can i access to that data? I mean how can i get names, ids, product_ids etc
How can i put that data (name) to my TableViewController?
I am using both SwiftyJSON and Alamofire in one of my projects. Here is how I am using it.
Create a protocol called APIProtocol.
Setup an API class with a GET method that accepts a delegate of type APIProtocol.
Setup TableViewController to implement the APIProtocol.
Call API.get() from TableViewController
Code
// Step 1
protocol APIProtocol {
func didReceiveResult(results: JSON)
}
// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
let url = "\(self.hostname)\(path)"
NSLog("Preparing for GET request to: \(url)")
Alamofire.request(.GET, url, parameters: parameters)
.responseJSON { (req, res, json, error) in
if(error != nil) {
NSLog("GET Error: \(error)")
println(res)
}
else {
var json = JSON(json!)
NSLog("GET Result: \(json)")
// Call delegate if it was passed into the call
if(delegate != nil) {
delegate!.didReceiveResult(json)
}
}
}
}
// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.
...
func didReceiveResult(result: JSON) {
var activities: NSMutableArray = []
NSLog("Activity.didReceiveResult: \(result)")
for (index: String, activity: JSON) in result {
var activityModel = ActivityModel(
id: activity["id"].intValue,
message: activity["message"].stringValue
)
activities.addObject(activityModel)
}
// Set our array of new models
activityModelList = activities
// Make sure we are on the main thread, and update the UI.
dispatch_sync(dispatch_get_main_queue(), {
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
})
}
}
// Step 4
override func viewDidLoad() {
MyAPI.get("/activities", delegate: self)
}
The accessors (for SwiftyJSON at least) work like:
if let userName = json[0]["528"]["name"].string{
println(userName) // "Name 1"
}
More information on how to use SwiftyJSOn can be found here in its official documentation: https://github.com/SwiftyJSON/SwiftyJSON
Regarding how to put that data into a UITableView, there are many methods. Set up a UITableView cell and then load in the JSON data in some sort of array for instance.
Check this repo for an example that declare how to use Alamofire in your code and how to create models with swift and parsing JSON response
Install Alamofire in your project
Import Alamofire in your class
Define these variables in you class
typealias complitionBlock = (data: AnyObject) -> Void
let KBASE_URL: String = "http://static.westwing.de/cms/dont-delete/programming_task/data.json"
Set the implementation for this function
func getMainItems(complition block: complitionBlock) {
Alamofire.request(.GET, KBASE_URL, parameters:nil).responseJSON { response in
do {
let items = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions()) as! NSArray
let mutableArray: NSMutableArray = []
items.enumerateObjectsUsingBlock({ object, index, stop in
let str = object as! NSDictionary
//Replace WESItem with your model
//let item = WESItem(dictionary: str as NSDictionary)
mutableArray.addObject(item)
})
block(data: mutableArray)
} catch {
print(error)
}
}
}
For more information:
https://github.com/AhmedAskar/WestWing
Following should work for you :-
var nameArr = [String]()
Alamofire.request(.GET,"your url", parameters: nil)
.validate().responseJSON { response in
if let responseJson = response.result.value {
let name = responseJson["name"] as! String
nameArr.append(name)
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}// Alamofire Close
Use tableview as you normally use it i.e.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
}
cell!.textLabel?.text = nameArr[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArr.count
}
Note: No need to use Swifty JSON as Alamofire allows JSON response which can be directly handled within ".responseJSON".
pod 'Alamofire' pod 'SwiftyJSON' pod 'ReachabilitySwift'
import UIKit import Alamofire import SwiftyJSON import SystemConfiguration
class WebServiceHelper: NSObject {
typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void
// MARK: - Internet Connectivity
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
// MARK: - Helper Methods
class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
print(strURL)
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL).responseJSON { (resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(resJson)
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(error)
failure(error)
}
}
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler){
if isConnectedToNetwork() {
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}
else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler)
{
if isConnectedToNetwork()
{
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
let resJson = JSON(resObj.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.upload(
multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.append(imageData, withName: "Image.jpg")
}
for (key, value) in params! {
let data = value as! String
multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
print(multipartFormData)
}
},
to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
//let datastring = String(data: response, encoding: String.Encoding.utf8)
// print(datastring)
}
case .failure(let encodingError):
print(encodingError)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { (response) -> Void in
if response.result.isSuccess
{
let resJson = JSON(response.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if response.result.isFailure
{
let error : Error = response.result.error! as Error
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
}
case .failure(let encodingError):
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
}
)
}
else
{
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
}
==================================
Call Method
let aParams : [String : String] = ["DeviceIDString", "DeviceType" : "iOS", ]
WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in
if "\(responceObj["RespCode"])" != "1"
{
let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
else
{
let aParams : [String : String] = [
"Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
]
CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)
}
}, failure:
{ (error) in
CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
})
}
// fatch json data swiftjson with alamofire
// First in using Alamofire
// second in fatch json data in tableView
// create json model classmodel1
//model2

Resources