problem when authorize then how to define provider in swifter.authorize method - authentication

i am facing problem to give provider name because i dont know how to give proper provider in swifter.authorize
my controller is where i am using login code
you can check func actiontwitter in which i have used provider then please suggest me how to use provider as parameter
i have installed swifter package in project
//
// twitterVc.swift
// socialLogin
//
// Created by ios on 19/11/22.
//
import UIKit
import FirebaseAuth
import Swifter
import SafariServices
struct TwitterConstants {
static let CONSUMER_KEY = "MY_CONSUMER_KEY"
static let CONSUMER_SECRET_KEY = "MY_CONSUMER_SECRET_KEY"
static let CALLBACK_URL = "MY_CALLBACK_URL"
}
class twitterVc: UIViewController {
var swifter: Swifter!
var accToken: Credential.OAuthAccessToken?
#IBOutlet weak var submitBtn: UIButton!
var provider = OAuthProvider(providerID: "twitter.com")
override func viewDidLoad() {
super.viewDidLoad()
self.isLoggedIn { loggedin in
if loggedin {
// Show the ViewController with the logged in user
print("Logged In?: YES")
} else {
// Show the Home ViewController
print("Logged In?: NO")
}
}
}
func isLoggedIn(completion: #escaping (Bool) -> ()) {
let userDefaults = UserDefaults.standard
let accessToken = userDefaults.string(forKey: "oauth_token") ?? ""
let accessTokenSecret = userDefaults.string(forKey: "oauth_token_secret") ?? ""
let swifter = Swifter(consumerKey: TwitterConstants.CONSUMER_KEY, consumerSecret: TwitterConstants.CONSUMER_SECRET_KEY, oauthToken: accessToken, oauthTokenSecret: accessTokenSecret)
swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { _ in
// Verify Succeed - Access Token is valid
completion(true)
}) { _ in
// Verify Failed - Access Token has expired
completion(false)
}
}
#IBAction func actionSubmit(_ sender: Any) {
self.actionTwitter()
}
func actionTwitter(){
//~~~~~~~~~~~~~~problem is here it is not taking provider as parameter
self.swifter.authorize(withProvider: provider as! ASWebAuthenticationPresentationContextProviding, callbackURL: URL(string: TwitterConstants.CALLBACK_URL)!) { (tokan: Credential.OAuthAccessToken?, resp: URLResponse) in
}
}
}
func failureHandler(){
}
extension twitterVc: SFSafariViewControllerDelegate{
func getUserProfile() {
self.swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { json in
let userDefaults = UserDefaults.standard
userDefaults.set(self.accToken?.key, forKey: "oauth_token")
userDefaults.set(self.accToken?.secret, forKey: "oauth_token_secret")
// Twitter Id
if let twitterId = json["id_str"].string {
print("Twitter Id: \(twitterId)")
} else {
// self.twitterId = "Not exists"
}
// Twitter Handle
if let twitterHandle = json["screen_name"].string {
print("Twitter Handle: \(twitterHandle)")
} else {
// self.twitterHandle = "Not exists"
}
// Twitter Name
if let twitterName = json["name"].string {
print("Twitter Name: \(twitterName)")
} else {
// self.twitterName = "Not exists"
}
// Twitter Email
if let twitterEmail = json["email"].string {
print("Twitter Email: \(twitterEmail)")
} else {
// self.twitterEmail = "Not exists"
}
// Twitter Profile Pic URL
if let twitterProfilePic = json["profile_image_url_https"].string?.replacingOccurrences(of: "_normal", with: "", options: .literal, range: nil) {
print("Twitter Profile URL: \(twitterProfilePic)")
} else {
// self.twitterProfilePicURL = "Not exists"
}
print("Twitter Access Token: \(self.accToken?.key ?? "Not exists")")
}) { error in
print("ERROR: \(error.localizedDescription)")
}
}
}

Related

SwiftUI Share variable Between Struct

import SwiftUI
struct ReserveView: View {
#State var searchT = ""
#State var isSearching = false
#State private var showCheckAlert = false
#Binding var roomnum:Int
#StateObject private var vm = ReserveViewModel(
service: ReserveService()
)
var body: some View {
VStack{
HStack{
TextField("Search", text:$searchT)
.padding(.leading, 30)
}
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(6)
.padding(.horizontal)
.onTapGesture(perform: {
isSearching = true
})
.overlay(
HStack {
Image(systemName: "magnifyingglass")
Spacer()
}.padding(.horizontal,32)
.foregroundColor(.white)
)
if isSearching {
Button(action:{
isSearching = false
searchT = ""
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for:nil)
}, label: {
Text("Cancle")
.padding(.trailing)
.padding(.leading,0)
})
.transition(.move(edge: .trailing))
}
switch vm.state{
case .success(let data):
List{
ForEach((data).filter({"\($0)".contains(searchT)||searchT.isEmpty}),
id: \.roomnum){ item in
HStack{
Text("\(item.when) \(item.time) \(item.username)").foregroundColor(Color.black)
}
}
}
.padding(.bottom,15)
//.padding(.top,20)
case .loading:
ProgressView()
default:
EmptyView()
}
}
.task {
await vm.getReserves()
}
}
}
struct ReserveView_Previews: PreviewProvider {
static var previews: some View {
ReserveView(roomnum:.constant(""))
}
}
import Foundation
import SwiftUI
struct ReserveService {
enum ReserveListError: Error {
case failed
case failedToDecode
case invalidStatusCode
}
func fetchReserves() async throws -> [Reserve] {
let url = URL(string: "https://f6d3-119-203-102/roomreserveview?roomnum=\(here i want use variable)")!
let configuration = URLSessionConfiguration.ephemeral
print(url)
let (data, response) = try await URLSession(configuration: configuration).data(from: url)
guard let response = response as? HTTPURLResponse,
response.statusCode == 200 else{
throw ReserveListError.invalidStatusCode
}
let decodedData = try JSONDecoder().decode(ReserveServiceResult.self, from: data)
return decodedData.reserveInfo
}
}
import SwiftUI
import Foundation
#MainActor
class ReserveViewModel: ObservableObject {
enum State {
case na
case loading
case success(data: [Reserve])
case failed(error: Error)
}
#Published private(set) var state: State = .na
#Published var hasError: Bool = false
private let service: ReserveService
init(service: ReserveService) {
self.service = service
}
func getReserves() async {
self.state = .loading
self.hasError = false
do {
let reserves = try await service.fetchReserves()
self.state = .success(data: reserves)
}catch {
self.state = .failed(error: error)
self.hasError = true
print(String(describing: error))
}
}
}
hello! I'd like to ask you a SwiftUI question.
Based on the ReserveService file, I am implementing the part that lists and displays the desired data in ReserveView.
I want to complete the url in the 'fetchReserves' function by receiving the variable 'roomnum' from the ReserveView model to the ReserveService.
However, Binding does not seem to work because ReserveService is not a view model. Is there any way I can get this variable from the viewmodel?
If you don't understand my explanation, please ask the question again.
This is my first time asking a question. Please forgive me if there is something missing in my question
It is possible to inject it as function argument, like
func fetchReserves(_ roomnum: Int) async throws -> [Reserve] {
let url = URL(string:
"https://f6d3-119-203-102/roomreserveview?roomnum=\(roomnum)")!

How to Display Post Method Requests data in Swiftui Ios Simulator Screen?

This is Doc File Generate in Postman by write method and url "link/services.php".
This is Header File.
#Headers({"Content-Type: application/json"})
 #POST("services.php")
Observable<Division> divisionListApi(#Body HashMap<String, String> map);
map.put("method", "My_List");
After Postman Generation I Got This Given Below.
{"err_code":9,
"message":"My List ",
"list":[
{"ForestDivision":"Yam(T)"},
{"ForestDivision":"Rewar(T)"},
{"ForestDivision":"Ro(T)"},
{"ForestDivision":"Bh(T)"},
{"ForestDivision":"Ka(T) "},
{"ForestDivision":"Ambal(T) "},
{"ForestDivision":"Fari(T)"}]
}
I have made request by taking post mehod, is this the right way to create code in
swiftui.
import Foundation
import Combine
struct File: Decodable, Hashable {
var error_code : Int
var message : String
var list : [lisst]
}
struct lisst: Decodable, Hashable {
var ForestDivision: String
}
class fetchResults : ObservableObject{
#Published var fetchedRes : [lisst]?
func getData(completion: #escaping (File) -> ()){
print("Fetch")
let parameters = "{ I dont Know }"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string:
"URl")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { (data, _, _) in
let resultList = try! JSONDecoder().decode(File.self, from: data!)
print(" ")
print("ID: \(resultList.error_code)")
print("VOLUME: \(resultList.message)")
print("READINGS: \(String(describing: resultList.list))")
print(" ")
print("SUCCESS: Got data - \(data! )")
DispatchQueue.main.async {
completion(resultList) // << here !!
}
}
task.resume()
}
}
Also How to Write in Swiftui View.
To Make Properly Works in List View.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var res = fetchResults()
var body: some View {
NavigationView {
Text("Nothing Here")
List(res.fetchedRes ?? [], id: \.self) { resp in // Error Here
ForEach(res.list, id: \.self) { course in
VStack {
Text(res.for) // Error Here
}
}
}
.navigationBarTitle("Data")
.onAppear(perform: {
self.getData // Error Here
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}
Create New Swift File Copy this Post Requests.
import Foundation
import Combine
let postUrl = "Your URl"
struct divisionList: Decodable, Identifiable {
let id: Int
let mesg: String
let list: [FDivision]
private enum CodingKeys: String, CodingKey {
case id = "err_code"
case mesg = "message"
case list = "list"
}
}
struct FDivision: Decodable, Hashable {
let forestDivision: String
private enum CodingKeys: String, CodingKey {
case forestDivision = "ForestDivision"
}
init(data:String) {
forestDivision = data
}
}
class viewModal: ObservableObject {
#Published var items = [FDivision]()
func postData() {
guard let serviceUrl = URL(string: postUrl) else { return }
let parameters: [String: Any] = [
"method": "Your Method Name"
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.timeoutInterval = 20
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let dictionary = json as? [String:Any] {
if let arrList = dictionary["list"] as? [[String:Any]]{
for data in arrList{
let model = FDivision(data: data["ForestDivision"] as! String)
self.items.append(model)
}
}
}
print(json)
} catch {
print(error)
}
}
}.resume()
}
}
Create Now New Swiftui File.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var vm = viewModal()
var body: some View {
NavigationView {
VStack {
List(vm.items, id: \.self) { item in
Button(action: {}, label: {
Text(item.forestDivision).foregroundColor(.customGreen)
})
}
}.navigationBarTitle("Data")
.onAppear(perform: {
vm.postData()
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}

How to make HTTP post request with specific body? And how to access token from the server to allow me to login?

I'm having a scenario like :
1) I want to create Http POST request and for this I'm having the data, please see this image:
2) As you can see in the above image, I have to create post a request with the mentioned body and also I'm getting response named: token. How to create post request and fetch this token response?.
3) That token response will allow me to login into myapp.
I'm newbie to this scenario. I have tried some code by my own but still getting confuse in how to combine my app delegate code with this POST Request Code.
Code
#IBAction func signinaction(_ sender: Any) {
self.username.resignFirstResponder()
self.password.resignFirstResponder()
if (self.username.text == "" || self.password.text == "") {
let alertView = UIAlertController(title: "Login failed",
message: "Wrong username or password." as String, preferredStyle:.alert)
let okAction = UIAlertAction(title: "Try Again!", style: .default, handler: nil)
alertView.addAction(okAction)
self.present(alertView, animated: true, completion: nil)
return
}
// Check if the user entered an email
if let actualUsername = self.username.text {
// Check if the user entered a password
if let actualPassword = self.password.text {
// Build the body message to request the token to the web app
self.bodyStr = "username=8870417698&password=1234&grant_type=password" + actualUsername + "&password=" + actualPassword
// Setup the request
let myURL = NSURL(string: "http://ezschoolportalapi.azurewebsites.net/token")!
let request = NSMutableURLRequest(url: myURL as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = bodyStr.data(using: String.Encoding.utf8)!
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if data?.count != 0
{
do {
let tokenDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
print(tokenDictionary)
// Get the token
let token:String = tokenDictionary["access_token"] as! String
// Keep record of the token
let userdefaults = UserDefaults()
let saveToken = userdefaults.set(token, forKey: "access_token")
userdefaults.synchronize()
// Dismiss login view and go to the home view controller
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
catch {
// Wrong credentials
// Reset the text fields
self.username.text = ""
self.password.text = ""
// Setup the alert
let alertView = UIAlertController(title: "Login failed",
message: "Wrong username or password." as String, preferredStyle:.alert)
let okAction = UIAlertAction(title: "Try Again!", style:.default, handler: nil)
alertView.addAction(okAction)
self.present(alertView, animated: true, completion: nil)
return
}
}
}
task.resume()
}
}
}
Question is how to combine this code with my above code :
let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.gotoMainvc()
if I use directly this code then in any of the case I'm able to switch over to my home screen it doesn't matter whether m using this POST Request code or not. Please Help.
You are hard coding the username and password in bodyStr update it to
self.bodyStr = "username=" + actualUsername + "&password=" + actualPassword + "&grant_type=password"
Update the statements inside do with
do {
let tokenDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
print(tokenDictionary)
// Get the token
if let authToken = tokenDictionary["access_token"] as? String{
self.token = authToken
UserDefaults.standard.set(accessToken, forKey: "access_token")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
}
You can implement a function like isUserLoggedIn which will return true if token is saved in userDefaults. You need to check whether the user has logged in in the appDelegate's applicationdidFinishLaunchingWithOptions.Like
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if isUserLoggedIn(){
//showHomeViewController
} else{
//showLoginViewController
}
return true
}
func isUserLoggedIn() -> Bool{
if let accessToken = UserDefaults.standard.object(forKey: "access_token") as? String {
if (accessToken.characters.count)! > 0{
return true
} else {
return false
}
}
else {
return false
}
}

Swift 3 NTLM authentication

For a recent project I tried to pull some data from a server in the SOAP and oData format respectively, that is protected with a Microsoft NTLM authentication, and it has been a nightmare figuring out how to do it, none of the online examples really worked.
So here is my solution; I had to adapt, expand and combine a few different sources. I hope this helps someone in the future.
You might have to allow arbitrary loads!!
Adapted from:
https://gist.github.com/stevenschobert/f374c999e5cba6ccf09653b846967c83
https://blogs.msdn.microsoft.com/chiranth/2013/09/20/ntlm-want-to-know-how-it-works/
import UIKit
class ViewController: UIViewController {
var username: String? = nil
var password: String? = nil
lazy var conn: URLSession = {
let config = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
return session
}()
override func viewDidLoad() {
super.viewDidLoad()
username = "<username>"
password = "<password>"
ntlm()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func ntlm() {
let urlString = "<url>"
let url = URL(string: urlString)
let request = NSMutableURLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60000)
request.httpMethod = "GET"
let task = conn.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
print(response)
print(error)
print(String(data: data!, encoding: .utf8))
})
task.resume()
}
func doesHaveCredentials() -> Bool {
guard let _ = self.username else { return false }
guard let _ = self.password else { return false }
return true
}
}
extension ViewController: URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("got challenge")
guard challenge.previousFailureCount == 0 else {
print("too many failures")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM else {
print("unknown authentication method \(challenge.protectionSpace.authenticationMethod)")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard self.doesHaveCredentials() else {
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
DispatchQueue.main.async {
print("Userdata not set")
};
return
}
let credentials = URLCredential(user: self.username!, password: self.password!, persistence: .forSession)
challenge.sender?.use(credentials, for: challenge)
completionHandler(.useCredential, credentials)
}
}

No Sim Card Installed Pop up showing twice in calling feature

I am using calling feature in App . Problem is that if no sim card installed in device then "No sim card installed" Alert view showing 2 times . I am using this code :
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:phoneNumber]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
}
Note: 1st Alert view automatically hide and again 2nd one is appearing .
Finally Found alternate solution for this :
Actually this is not an issue , This is transition effect :
To resolve it i have integrated below code before calling feature :
#import CoreTelephony;
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No SIM Card Installed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
}
import UIKit
import Alamofire
import NVActivityIndicatorView
import Reachability
//pod 'NVActivityIndicatorView'
//pod 'Alamofire', '~> 4.0'
//pod 'ReachabilitySwift'
typealias CompletionHandler = (_ success:Bool,_ reponsedata:Data) -> Void
typealias CompletionHandlerJson = (_ success:Bool,_ reponsedata:NSMutableDictionary) -> Void
typealias ResponseHandler = (_ success:Bool,_ data:NSData, _ error : String) -> Void
typealias ConnectivityHandler = (_ success:Bool) -> Void
class Connectivity {
class func internetConnection(completionHandler: #escaping ConnectivityHandler) {
//var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "HEAD"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 1.0
let session = URLSession.shared
session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
completionHandler(true)
}
}
completionHandler(false)
}).resume()
}
class func connetivityAvailable() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
class WebserviceHelper: NSObject {
class func postWebServiceCall(urlString:String, parameters:[String:AnyObject], encodingType: String, ShowProgress:Bool, completionHandler: #escaping CompletionHandler){
if Connectivity.connetivityAvailable() == false {
log(message: "internet is not available.")
HUD.hide()
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,Data())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
let encoding: ParameterEncoding!
if encodingType == DefaultEncoding{
encoding = JSONEncoding.default
}else{
encoding = URLEncoding.httpBody
}
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, encoding: encoding , headers: HelperClass.sharedInstance.getApiHeader()).responseData(completionHandler: { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value {
completionHandler(true,result)
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,Data())
}
completionHandler(false,Data())
}
})
}
class func postWebServiceJson(urlString:String, parameters:[String:AnyObject], encodingType: String, ShowProgress:Bool, completionHandler: #escaping CompletionHandlerJson){
if Connectivity.connetivityAvailable() == false {
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,NSMutableDictionary())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
let encoding: ParameterEncoding!
if encodingType == DefaultEncoding{
encoding = JSONEncoding.default
}else{
encoding = URLEncoding.httpBody
}
Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, encoding: encoding , headers: HelperClass.sharedInstance.getApiHeader()).responseJSON { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value as? NSDictionary {
completionHandler(true,NSMutableDictionary(dictionary: result))
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,NSMutableDictionary())
}
completionHandler(false,NSMutableDictionary())
}
}
}
class func WebapiGetMethod(strurl:String, ShowProgress: Bool = false, completionHandler: #escaping CompletionHandlerJson){
if Connectivity.connetivityAvailable() == false {
log(message:"internet is not available.")
completionHandler(false,NSMutableDictionary())
//.. AppDelegate .showMessage(message:"Please check your internet connection")
return
}
if ShowProgress{
HUD.show(.systemActivity)
}
Alamofire.request(strurl).responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 200:
if let result = response.result.value {
if let JSONdict = result as? NSMutableDictionary{
DispatchQueue.main.async {
completionHandler(true,JSONdict)
}
}
if ShowProgress {
HUD.hide()
}
}else{
if ShowProgress {
HUD.hide()
}
completionHandler(false,NSMutableDictionary())
}
log(message:"example success")
default:
log(message:"error with get response status: \(status)")
DispatchQueue.main.async {
if ShowProgress {
HUD.hide()
}
}
completionHandler(false,NSMutableDictionary())
}
}
DispatchQueue.main.async {
if ShowProgress {
HUD.hide()
}
}
}
}
class func getWebServiceCall(urlString:String,ShowProgress:Bool, completionHandler: #escaping CompletionHandler){
if Connectivity.connetivityAvailable() == false {
log(message: "internet is not available.")
HUD.hide()
AppDelegate.showMessage(message:NO_INTERNET_AVAILABLE)
completionHandler(false,Data())
return
}
if ShowProgress {
HUD.show(.systemActivity)
}
log(message: "\(urlString): + parametersnew")
Alamofire.request(urlString, method: .get, parameters: nil, encoding: URLEncoding.methodDependent, headers: HelperClass.sharedInstance.getApiHeader()).responseData { (response) in
if response.result.isSuccess {
if ShowProgress {
HUD.hide()
}
if let result = response.result.value {
completionHandler(true,result)
}
}
if response.result.isFailure {
if ShowProgress{
HUD.hide()
}
print("Lost Connection %#",urlString)
if let responseCode = response.response?.statusCode as Int?{
print("Lost Connection with code %#",response.result.value as Any)
let responseDic = NSMutableDictionary()
responseDic.setObject(responseCode, forKey: "statusCode" as NSCopying)
completionHandler(false,Data())
}
completionHandler(false,Data())
}
}
}
}