kandi background
Explore Kits

AppUpdate | Android 版本更新 a library for android version update | Widget library

 by   WVector Java Version: V3.2.7 License: No License

 by   WVector Java Version: V3.2.7 License: No License

Download this library from

kandi X-RAY | AppUpdate Summary

AppUpdate is a Java library typically used in User Interface, Widget applications. AppUpdate has no vulnerabilities, it has build file available and it has medium support. However AppUpdate has 1 bugs. You can download it from GitHub.
🚀 Android 版本更新 🚀 a library for android version update 🚀
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • AppUpdate has a medium active ecosystem.
  • It has 3289 star(s) with 700 fork(s). There are 82 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 81 open issues and 48 have been closed. On average issues are closed in 6 days. There are 2 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of AppUpdate is V3.2.7
AppUpdate Support
Best in #Widget
Average in #Widget
AppUpdate Support
Best in #Widget
Average in #Widget

quality kandi Quality

  • AppUpdate has 1 bugs (0 blocker, 0 critical, 1 major, 0 minor) and 78 code smells.
AppUpdate Quality
Best in #Widget
Average in #Widget
AppUpdate Quality
Best in #Widget
Average in #Widget

securitySecurity

  • AppUpdate has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • AppUpdate code analysis shows 0 unresolved vulnerabilities.
  • There are 10 security hotspots that need review.
AppUpdate Security
Best in #Widget
Average in #Widget
AppUpdate Security
Best in #Widget
Average in #Widget

license License

  • AppUpdate does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.
AppUpdate License
Best in #Widget
Average in #Widget
AppUpdate License
Best in #Widget
Average in #Widget

buildReuse

  • AppUpdate releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • AppUpdate saves you 920 person hours of effort in developing the same functionality from scratch.
  • It has 2099 lines of code, 205 functions and 29 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
AppUpdate Reuse
Best in #Widget
Average in #Widget
AppUpdate Reuse
Best in #Widget
Average in #Widget
Top functions reviewed by kandi - BETA

kandi has reviewed AppUpdate and discovered the below as its top functions. This is intended to give you an instant insight into AppUpdate implemented functionality, and help decide if they suit your requirements.

  • update Diy
  • Check if new app is available .
  • Start download app .
  • Calculate the draw rectangle F .
  • Set up notification channel
  • show progress dialog
  • Download file .
  • Converts a drawable to a bitmap
  • Returns the MD5 of the specified file .
  • show horizontal progress dialog

AppUpdate Key Features

🚀 Android 版本更新 🚀 a library for android version update 🚀

Gradle 依赖

copy iconCopydownload iconDownload
dependencies {
    compile 'com.qianwen:update-app:3.5.2'
}

简单使用

copy iconCopydownload iconDownload
	new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(mUpdateUrl)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .build()
                .update();

更新日志

copy iconCopydownload iconDownload
1,修复下载过程中,关闭对话框不能自动安装问题。

License

copy iconCopydownload iconDownload
Copyright 2017 千匍

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

removing item from ListView.builder Flutter

copy iconCopydownload iconDownload
ListView.builder(
  itemCount: state.services.count,
  itemBuilder: (BuildContext context, int index) =>
    Dismissible(
      key: Key(state.service.toString()),
      onDismissed: (direction) {
         // Remove the item from the data source.
         setState(() {
             x.removeAt(index);
         });
        },
        child: //your child here (maybe listivew)
     ),
   ),

Fatal Exception: java.lang.NullPointerException in release build

copy iconCopydownload iconDownload
Fatal Exception: java.lang.NullPointerException throw with null 
exceptionin.hopq.hopq.authentication.models.AppUpdateSourceDO$AppUpdate.getMinAllowedVersion (AppUpdateSourceDO.java:3)
data class AppUpdate(
        @SerializedName("excluded_versions")
        val excludedVersions: List<ExcludedVersion> = listOf(),
        @SerializedName("min_allowed_version")
        val minAllowedVersion: Int? = null,
        @SerializedName("min_allowed_version_ios")
        val minAllowedVersionIos: String? = null,
        @SerializedName("recommended_version")
        val recommendedVersion: Int? = null
)
-----------------------
Fatal Exception: java.lang.NullPointerException throw with null 
exceptionin.hopq.hopq.authentication.models.AppUpdateSourceDO$AppUpdate.getMinAllowedVersion (AppUpdateSourceDO.java:3)
data class AppUpdate(
        @SerializedName("excluded_versions")
        val excludedVersions: List<ExcludedVersion> = listOf(),
        @SerializedName("min_allowed_version")
        val minAllowedVersion: Int? = null,
        @SerializedName("min_allowed_version_ios")
        val minAllowedVersionIos: String? = null,
        @SerializedName("recommended_version")
        val recommendedVersion: Int? = null
)
-----------------------
# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}
-----------------------
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
 }
-keepclassmembers class MyDataClass {
  !transient <fields>;
 }
-----------------------
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
 }
-keepclassmembers class MyDataClass {
  !transient <fields>;
 }
-----------------------
##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { <fields>; }

# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}

##---------------End: proguard configuration for Gson  ----------
-----------------------
-keepclassmembers,allowobfuscation class * {
    @com.google.gson.annotations.SerializedName <fields>;
  }
-keep,allowobfuscation @interface com.google.gson.annotations.SerializedName
-----------------------
-keepclassmembers enum * { *; }

iOS create generic Alamofire request using swift

copy iconCopydownload iconDownload
import Alamofire

class NetworkManager : NSObject {
internal typealias SuccessCompletion = (Int?, Any?) -> Void?
internal typealias FailCompletion = (Int?, Error, Any?) -> Void?
var sessionManager : SessionManager!
var request : Request?
var headers : HTTPHeaders! = [:]


    override init() {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        sessionManager = SessionManager(configuration: configuration)
     }


func sendRequest(url: String?, method: String, parameters: [String: Any], success: SuccessCompletion?, fail: FailCompletion?){
    var encoding : ParameterEncoding!
    if  HTTPMethod(rawValue: method) == HTTPMethod.post {
        encoding = JSONEncoding.default
    } else {
        encoding = URLEncoding.default
    }

    request = sessionManager.request(url ?? "", method: HTTPMethod(rawValue: method)!, parameters: parameters, encoding: encoding, headers: headers)
    .validate()
    .responseData{response in
        switch (response.result) {
        case .success:
            let statusCode = response.response?.statusCode
            success?(statusCode, response.result.value)
            self.request = nil
            break
        case .failure(let error):
            let statusCode = response.response?.statusCode
            fail?(statusCode, error, response.data)
            self.request = nil
            break
        }
    }
}

}
func updateJSONHeader(token: String) {
        self.clearHeaders()
        headers["AuthorizationToken"] = "\(token)"
    }
func setCookie(_ cookie : HTTPCookie?){
    if let cookie = cookie {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}
func clearHeaders(){
    headers = [:]
}
-----------------------
import Alamofire

class NetworkManager : NSObject {
internal typealias SuccessCompletion = (Int?, Any?) -> Void?
internal typealias FailCompletion = (Int?, Error, Any?) -> Void?
var sessionManager : SessionManager!
var request : Request?
var headers : HTTPHeaders! = [:]


    override init() {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        sessionManager = SessionManager(configuration: configuration)
     }


func sendRequest(url: String?, method: String, parameters: [String: Any], success: SuccessCompletion?, fail: FailCompletion?){
    var encoding : ParameterEncoding!
    if  HTTPMethod(rawValue: method) == HTTPMethod.post {
        encoding = JSONEncoding.default
    } else {
        encoding = URLEncoding.default
    }

    request = sessionManager.request(url ?? "", method: HTTPMethod(rawValue: method)!, parameters: parameters, encoding: encoding, headers: headers)
    .validate()
    .responseData{response in
        switch (response.result) {
        case .success:
            let statusCode = response.response?.statusCode
            success?(statusCode, response.result.value)
            self.request = nil
            break
        case .failure(let error):
            let statusCode = response.response?.statusCode
            fail?(statusCode, error, response.data)
            self.request = nil
            break
        }
    }
}

}
func updateJSONHeader(token: String) {
        self.clearHeaders()
        headers["AuthorizationToken"] = "\(token)"
    }
func setCookie(_ cookie : HTTPCookie?){
    if let cookie = cookie {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}
func clearHeaders(){
    headers = [:]
}
-----------------------
import Alamofire

class NetworkManager : NSObject {
internal typealias SuccessCompletion = (Int?, Any?) -> Void?
internal typealias FailCompletion = (Int?, Error, Any?) -> Void?
var sessionManager : SessionManager!
var request : Request?
var headers : HTTPHeaders! = [:]


    override init() {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        sessionManager = SessionManager(configuration: configuration)
     }


func sendRequest(url: String?, method: String, parameters: [String: Any], success: SuccessCompletion?, fail: FailCompletion?){
    var encoding : ParameterEncoding!
    if  HTTPMethod(rawValue: method) == HTTPMethod.post {
        encoding = JSONEncoding.default
    } else {
        encoding = URLEncoding.default
    }

    request = sessionManager.request(url ?? "", method: HTTPMethod(rawValue: method)!, parameters: parameters, encoding: encoding, headers: headers)
    .validate()
    .responseData{response in
        switch (response.result) {
        case .success:
            let statusCode = response.response?.statusCode
            success?(statusCode, response.result.value)
            self.request = nil
            break
        case .failure(let error):
            let statusCode = response.response?.statusCode
            fail?(statusCode, error, response.data)
            self.request = nil
            break
        }
    }
}

}
func updateJSONHeader(token: String) {
        self.clearHeaders()
        headers["AuthorizationToken"] = "\(token)"
    }
func setCookie(_ cookie : HTTPCookie?){
    if let cookie = cookie {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}
func clearHeaders(){
    headers = [:]
}
-----------------------
import Alamofire

class NetworkManager : NSObject {
internal typealias SuccessCompletion = (Int?, Any?) -> Void?
internal typealias FailCompletion = (Int?, Error, Any?) -> Void?
var sessionManager : SessionManager!
var request : Request?
var headers : HTTPHeaders! = [:]


    override init() {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        sessionManager = SessionManager(configuration: configuration)
     }


func sendRequest(url: String?, method: String, parameters: [String: Any], success: SuccessCompletion?, fail: FailCompletion?){
    var encoding : ParameterEncoding!
    if  HTTPMethod(rawValue: method) == HTTPMethod.post {
        encoding = JSONEncoding.default
    } else {
        encoding = URLEncoding.default
    }

    request = sessionManager.request(url ?? "", method: HTTPMethod(rawValue: method)!, parameters: parameters, encoding: encoding, headers: headers)
    .validate()
    .responseData{response in
        switch (response.result) {
        case .success:
            let statusCode = response.response?.statusCode
            success?(statusCode, response.result.value)
            self.request = nil
            break
        case .failure(let error):
            let statusCode = response.response?.statusCode
            fail?(statusCode, error, response.data)
            self.request = nil
            break
        }
    }
}

}
func updateJSONHeader(token: String) {
        self.clearHeaders()
        headers["AuthorizationToken"] = "\(token)"
    }
func setCookie(_ cookie : HTTPCookie?){
    if let cookie = cookie {
        HTTPCookieStorage.shared.setCookie(cookie)
    }
}
func clearHeaders(){
    headers = [:]
}
-----------------------
enum Router: URLRequestConvertible { 

//your all endpoint
static var authToken = ""
case login([String:Any])

var route: Route {
        switch self {
        case .Login(let dict):
            return Route(endPoint: "api/addimagedata", httpMethod: .post)
        }
    }

func asURLRequest() throws -> URLRequest {

        var requestUrl = EnvironmentVariables.baseURL
        if let queryparams = route.queryParameters {
            requestUrl.appendQueryParameters(queryparams)
        }
        var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
        mutableURLRequest.httpMethod = route.method.rawValue


        //FIXME:- Change the Userdefault Key
        if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
            Router.authToken = token
        }

        //FIXME:- Set Mutable Request Accordingly
        mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")

        if route.method == .get {
            return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
        }
        return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
    }


}
struct Route {

    let endPath: String
    let method: Alamofire.HTTPMethod
    var parameters: Parameters?
    var queryParameters : [String:String]?

    var encoding: Alamofire.ParameterEncoding {
        switch method {
        case .post, .put, .patch, .delete:
            return JSONEncoding()
        default:
            return URLEncoding()
        }
    }
}
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : @escaping (M) -> ()) {

    view.endEditing(true)

    if !isConnectedToInternet {
        showNetworkError()
        return
    }

    if showhud ? showHud() : ()

    Alamofire.request(router).responseObject { (response: DataResponse<M>) in

        self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
            if isSuccess {
                if let value = response.result.value {
                    responseModel(value)
                }
            }
        })
    }
}
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : @escaping (Bool) -> ()) {

        print(response)
        hideHud()
        switch response.response?.statusCode ?? 0 {
        case 200...299:
            isSuccess(true)
        case 401:
            isSuccess(false)
            showSessionTimeOutError()
        case -1005,-1001,-1003:
            break
        default:
            isSuccess(false)
            // Parse your response and show error in some way.

        }
    }
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
    print(response)
}
-----------------------
enum Router: URLRequestConvertible { 

//your all endpoint
static var authToken = ""
case login([String:Any])

var route: Route {
        switch self {
        case .Login(let dict):
            return Route(endPoint: "api/addimagedata", httpMethod: .post)
        }
    }

func asURLRequest() throws -> URLRequest {

        var requestUrl = EnvironmentVariables.baseURL
        if let queryparams = route.queryParameters {
            requestUrl.appendQueryParameters(queryparams)
        }
        var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
        mutableURLRequest.httpMethod = route.method.rawValue


        //FIXME:- Change the Userdefault Key
        if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
            Router.authToken = token
        }

        //FIXME:- Set Mutable Request Accordingly
        mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")

        if route.method == .get {
            return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
        }
        return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
    }


}
struct Route {

    let endPath: String
    let method: Alamofire.HTTPMethod
    var parameters: Parameters?
    var queryParameters : [String:String]?

    var encoding: Alamofire.ParameterEncoding {
        switch method {
        case .post, .put, .patch, .delete:
            return JSONEncoding()
        default:
            return URLEncoding()
        }
    }
}
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : @escaping (M) -> ()) {

    view.endEditing(true)

    if !isConnectedToInternet {
        showNetworkError()
        return
    }

    if showhud ? showHud() : ()

    Alamofire.request(router).responseObject { (response: DataResponse<M>) in

        self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
            if isSuccess {
                if let value = response.result.value {
                    responseModel(value)
                }
            }
        })
    }
}
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : @escaping (Bool) -> ()) {

        print(response)
        hideHud()
        switch response.response?.statusCode ?? 0 {
        case 200...299:
            isSuccess(true)
        case 401:
            isSuccess(false)
            showSessionTimeOutError()
        case -1005,-1001,-1003:
            break
        default:
            isSuccess(false)
            // Parse your response and show error in some way.

        }
    }
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
    print(response)
}
-----------------------
enum Router: URLRequestConvertible { 

//your all endpoint
static var authToken = ""
case login([String:Any])

var route: Route {
        switch self {
        case .Login(let dict):
            return Route(endPoint: "api/addimagedata", httpMethod: .post)
        }
    }

func asURLRequest() throws -> URLRequest {

        var requestUrl = EnvironmentVariables.baseURL
        if let queryparams = route.queryParameters {
            requestUrl.appendQueryParameters(queryparams)
        }
        var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
        mutableURLRequest.httpMethod = route.method.rawValue


        //FIXME:- Change the Userdefault Key
        if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
            Router.authToken = token
        }

        //FIXME:- Set Mutable Request Accordingly
        mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")

        if route.method == .get {
            return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
        }
        return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
    }


}
struct Route {

    let endPath: String
    let method: Alamofire.HTTPMethod
    var parameters: Parameters?
    var queryParameters : [String:String]?

    var encoding: Alamofire.ParameterEncoding {
        switch method {
        case .post, .put, .patch, .delete:
            return JSONEncoding()
        default:
            return URLEncoding()
        }
    }
}
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : @escaping (M) -> ()) {

    view.endEditing(true)

    if !isConnectedToInternet {
        showNetworkError()
        return
    }

    if showhud ? showHud() : ()

    Alamofire.request(router).responseObject { (response: DataResponse<M>) in

        self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
            if isSuccess {
                if let value = response.result.value {
                    responseModel(value)
                }
            }
        })
    }
}
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : @escaping (Bool) -> ()) {

        print(response)
        hideHud()
        switch response.response?.statusCode ?? 0 {
        case 200...299:
            isSuccess(true)
        case 401:
            isSuccess(false)
            showSessionTimeOutError()
        case -1005,-1001,-1003:
            break
        default:
            isSuccess(false)
            // Parse your response and show error in some way.

        }
    }
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
    print(response)
}
-----------------------
enum Router: URLRequestConvertible { 

//your all endpoint
static var authToken = ""
case login([String:Any])

var route: Route {
        switch self {
        case .Login(let dict):
            return Route(endPoint: "api/addimagedata", httpMethod: .post)
        }
    }

func asURLRequest() throws -> URLRequest {

        var requestUrl = EnvironmentVariables.baseURL
        if let queryparams = route.queryParameters {
            requestUrl.appendQueryParameters(queryparams)
        }
        var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
        mutableURLRequest.httpMethod = route.method.rawValue


        //FIXME:- Change the Userdefault Key
        if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
            Router.authToken = token
        }

        //FIXME:- Set Mutable Request Accordingly
        mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")

        if route.method == .get {
            return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
        }
        return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
    }


}
struct Route {

    let endPath: String
    let method: Alamofire.HTTPMethod
    var parameters: Parameters?
    var queryParameters : [String:String]?

    var encoding: Alamofire.ParameterEncoding {
        switch method {
        case .post, .put, .patch, .delete:
            return JSONEncoding()
        default:
            return URLEncoding()
        }
    }
}
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : @escaping (M) -> ()) {

    view.endEditing(true)

    if !isConnectedToInternet {
        showNetworkError()
        return
    }

    if showhud ? showHud() : ()

    Alamofire.request(router).responseObject { (response: DataResponse<M>) in

        self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
            if isSuccess {
                if let value = response.result.value {
                    responseModel(value)
                }
            }
        })
    }
}
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : @escaping (Bool) -> ()) {

        print(response)
        hideHud()
        switch response.response?.statusCode ?? 0 {
        case 200...299:
            isSuccess(true)
        case 401:
            isSuccess(false)
            showSessionTimeOutError()
        case -1005,-1001,-1003:
            break
        default:
            isSuccess(false)
            // Parse your response and show error in some way.

        }
    }
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
    print(response)
}
-----------------------
enum Router: URLRequestConvertible { 

//your all endpoint
static var authToken = ""
case login([String:Any])

var route: Route {
        switch self {
        case .Login(let dict):
            return Route(endPoint: "api/addimagedata", httpMethod: .post)
        }
    }

func asURLRequest() throws -> URLRequest {

        var requestUrl = EnvironmentVariables.baseURL
        if let queryparams = route.queryParameters {
            requestUrl.appendQueryParameters(queryparams)
        }
        var mutableURLRequest = URLRequest(url: requestUrl.appendingPathComponent(route.endPath))
        mutableURLRequest.httpMethod = route.method.rawValue


        //FIXME:- Change the Userdefault Key
        if Router.authToken.isEmpty, let token = UserDefaults.standard.string(forKey: "Key"), !token.isEmpty {
            Router.authToken = token
        }

        //FIXME:- Set Mutable Request Accordingly
        mutableURLRequest.setValue("Bearer \(Router.authToken)", forHTTPHeaderField: "Authorization")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")

        if route.method == .get {
            return try Alamofire.URLEncoding.default.encode(mutableURLRequest, with: route.parameters)
        }
        return try Alamofire.JSONEncoding.default.encode(mutableURLRequest, with: route.parameters)
    }


}
struct Route {

    let endPath: String
    let method: Alamofire.HTTPMethod
    var parameters: Parameters?
    var queryParameters : [String:String]?

    var encoding: Alamofire.ParameterEncoding {
        switch method {
        case .post, .put, .patch, .delete:
            return JSONEncoding()
        default:
            return URLEncoding()
        }
    }
}
func GenericApiCallForObject<T : URLRequestConvertible, M : EVObject>(router : T, showHud : Bool = true ,responseModel : @escaping (M) -> ()) {

    view.endEditing(true)

    if !isConnectedToInternet {
        showNetworkError()
        return
    }

    if showhud ? showHud() : ()

    Alamofire.request(router).responseObject { (response: DataResponse<M>) in

        self.HandleResponseWithErrorForObject(response: response) { (isSuccess) in
            if isSuccess {
                if let value = response.result.value {
                    responseModel(value)
                }
            }
        })
    }
}
func HandleResponseWithErrorForObject<M : EVObject>(response : DataResponse<M>, isSuccess : @escaping (Bool) -> ()) {

        print(response)
        hideHud()
        switch response.response?.statusCode ?? 0 {
        case 200...299:
            isSuccess(true)
        case 401:
            isSuccess(false)
            showSessionTimeOutError()
        case -1005,-1001,-1003:
            break
        default:
            isSuccess(false)
            // Parse your response and show error in some way.

        }
    }
GenericApiCallForObject(router: Router.Login(["xyz":"xyz"])) { (response : GeneralModel) in
    print(response)
}
-----------------------
public enum RESTError: Error {
    case BadRequest(String, [String]?)
    case InternalError(String)
    case UnAuthorized(String, [String]?)
    case NotFound(String)
    case Success

    /// <#Description#>
    ///
    /// - Parameters:
    ///   - code: <#code description#>
    ///   - message: <#message description#>
    ///   - globalErrors: <#globalErrors description#>
    /// - Returns: <#return value description#>
    public static func fromCode(code: Int, message: String, globalErrors: [String]? = nil) -> RESTError {
        switch code {
        case 400: return RESTError.BadRequest(message, globalErrors)
        case 401: return RESTError.UnAuthorized(message, globalErrors)
        case 500: return RESTError.InternalError(message)
        case 404: return RESTError.NotFound(message)
        default: break
        }
        return RESTError.Success
    }
}

Alamofire.request(urlRequest)
                        .validate(statusCode: 200...500)
                        .responseJSON(completionHandler: { (response: (DataResponse<Any>)) in
                            if let statusCode = response.response?.statusCode {
                                if statusCode != 200 {
                                    // call handler errors function with specific message
                                    if let arrayDictionary = response.result.value as? Dictionary<String,AnyObject> {
                                        var error: RESTError?
                                        if let code = arrayDictionary["status"] as? Int {
                                            let message = arrayDictionary["message"] as! String
                                            let globalErrors = arrayDictionary["globalErrors"] as? [String]
                                            error = RESTError.fromCode(code: code, message: message, globalErrors: globalErrors)
                                        } else {
                                            // Build from error message without code.
                                            let message = arrayDictionary["error_description"] as! String
                                            let codeMsg = arrayDictionary["error"] as! String
                                            let globalErrors = arrayDictionary["globalErrors"] as? [String]
                                            if codeMsg == "invalid_token" && message.starts(with: "Access token expired") {

                                                return
                                            } else {
                                                error = RESTError.fromCode(code: codeMsg, message: message, globalErrors: globalErrors)
                                            }
                                        }
                                        if let _ = error {
                                            errorHandler(error!)
                                        } else {
                                            errorHandler(RESTError.InternalError("Internal API rest error."))
                                        }
                                    } else {
                                        errorHandler(RESTError.fromCode(code: statusCode, message: ""))
                                    }
                                } else {
                                    if let arrayDictionary = response.result.value as? Dictionary<String,AnyObject> {
                                        handler(arrayDictionary)
                                    }
                                }
                            } else {
                                if let error = response.error {
                                    errorHandler(RESTError.InternalError(error.localizedDescription))
                                }
                            }
                        })
-----------------------
func customValidate() -> Self {
        return self.validate { _, response, data -> Request.ValidationResult in
            guard (400...599) ~= response.statusCode else { return .success(()) }
            guard let data = data else { return .failure(MyAppGeneralError.generalResponseError) }

            guard let errorResponse = try? JSONDecoder().decode(MyAppResponseError.self, from: data) else {
                return .failure(MyAppGeneralError.generalResponseError)
            }

            if response.statusCode == 401 {
                return .failure(MyAppGeneralError.unauthorizedAccessError(errorResponse))
            }

            return .failure(MyAppGeneralError.responseError(errorResponse))
        }
    }
class APIClient {
    var session: Session

    init(session: Session = Session.default) {
        self.session = session
    }

    @discardableResult
    func performRequest<T: Decodable>(request: URLRequestConvertible,
                                      decoder: JSONDecoder = JSONDecoder(),
                                      completion: @escaping (Result<T, AFError>) -> Void) -> DataRequest {
        return AF.request(request).customValidate().responseDecodable(decoder: decoder, completionHandler: { (response: DataResponse<T, AFError>) in
            completion(response.result)
        })
    }

    func getProfile(userID: Int, _ completion: @escaping (Result<UserToken, AFError>) -> Void) {
        performRequest(request: APIRouter.profile(userID: userID), completion: completion)
    }
}
enum APIRouter: URLRequestConvertible {
    case profile(userId :Int)

    static let baseURLString = "https://myserver.com"

    var method: HTTPMethod {
        switch self {
        case .profile:
            return .get
        }
    }

    var path: String {
        switch self {
        case .profile(let userID):
            return "profile/\(userID)"
        }
    }

    var body: Parameters {
        return [:]
    }

    // MARK: URLRequestConvertible
    func asURLRequest() throws -> URLRequest {
        let url = try APIRouter.baseURLString.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue

        // Common Headers
        urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")


        // Encode body
        urlRequest = try JSONEncoding.default.encode(urlRequest, with: body)

        return urlRequest
    }
}
-----------------------
func customValidate() -> Self {
        return self.validate { _, response, data -> Request.ValidationResult in
            guard (400...599) ~= response.statusCode else { return .success(()) }
            guard let data = data else { return .failure(MyAppGeneralError.generalResponseError) }

            guard let errorResponse = try? JSONDecoder().decode(MyAppResponseError.self, from: data) else {
                return .failure(MyAppGeneralError.generalResponseError)
            }

            if response.statusCode == 401 {
                return .failure(MyAppGeneralError.unauthorizedAccessError(errorResponse))
            }

            return .failure(MyAppGeneralError.responseError(errorResponse))
        }
    }
class APIClient {
    var session: Session

    init(session: Session = Session.default) {
        self.session = session
    }

    @discardableResult
    func performRequest<T: Decodable>(request: URLRequestConvertible,
                                      decoder: JSONDecoder = JSONDecoder(),
                                      completion: @escaping (Result<T, AFError>) -> Void) -> DataRequest {
        return AF.request(request).customValidate().responseDecodable(decoder: decoder, completionHandler: { (response: DataResponse<T, AFError>) in
            completion(response.result)
        })
    }

    func getProfile(userID: Int, _ completion: @escaping (Result<UserToken, AFError>) -> Void) {
        performRequest(request: APIRouter.profile(userID: userID), completion: completion)
    }
}
enum APIRouter: URLRequestConvertible {
    case profile(userId :Int)

    static let baseURLString = "https://myserver.com"

    var method: HTTPMethod {
        switch self {
        case .profile:
            return .get
        }
    }

    var path: String {
        switch self {
        case .profile(let userID):
            return "profile/\(userID)"
        }
    }

    var body: Parameters {
        return [:]
    }

    // MARK: URLRequestConvertible
    func asURLRequest() throws -> URLRequest {
        let url = try APIRouter.baseURLString.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue

        // Common Headers
        urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")


        // Encode body
        urlRequest = try JSONEncoding.default.encode(urlRequest, with: body)

        return urlRequest
    }
}
-----------------------
func customValidate() -> Self {
        return self.validate { _, response, data -> Request.ValidationResult in
            guard (400...599) ~= response.statusCode else { return .success(()) }
            guard let data = data else { return .failure(MyAppGeneralError.generalResponseError) }

            guard let errorResponse = try? JSONDecoder().decode(MyAppResponseError.self, from: data) else {
                return .failure(MyAppGeneralError.generalResponseError)
            }

            if response.statusCode == 401 {
                return .failure(MyAppGeneralError.unauthorizedAccessError(errorResponse))
            }

            return .failure(MyAppGeneralError.responseError(errorResponse))
        }
    }
class APIClient {
    var session: Session

    init(session: Session = Session.default) {
        self.session = session
    }

    @discardableResult
    func performRequest<T: Decodable>(request: URLRequestConvertible,
                                      decoder: JSONDecoder = JSONDecoder(),
                                      completion: @escaping (Result<T, AFError>) -> Void) -> DataRequest {
        return AF.request(request).customValidate().responseDecodable(decoder: decoder, completionHandler: { (response: DataResponse<T, AFError>) in
            completion(response.result)
        })
    }

    func getProfile(userID: Int, _ completion: @escaping (Result<UserToken, AFError>) -> Void) {
        performRequest(request: APIRouter.profile(userID: userID), completion: completion)
    }
}
enum APIRouter: URLRequestConvertible {
    case profile(userId :Int)

    static let baseURLString = "https://myserver.com"

    var method: HTTPMethod {
        switch self {
        case .profile:
            return .get
        }
    }

    var path: String {
        switch self {
        case .profile(let userID):
            return "profile/\(userID)"
        }
    }

    var body: Parameters {
        return [:]
    }

    // MARK: URLRequestConvertible
    func asURLRequest() throws -> URLRequest {
        let url = try APIRouter.baseURLString.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue

        // Common Headers
        urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")


        // Encode body
        urlRequest = try JSONEncoding.default.encode(urlRequest, with: body)

        return urlRequest
    }
}
-----------------------
let req = Alamofire.request(url, method: .get, parameters: nil)
req.response?.statusCode
req.responseString(completionHandler: <#T##(DataResponse<String>) -> Void#>)
  or
req.responseJSON(completionHandler: <#T##(DataResponse<Any>) -> Void#>)
-----------------------
let req = Alamofire.request(url, method: .get, parameters: nil)
req.response?.statusCode
req.responseString(completionHandler: <#T##(DataResponse<String>) -> Void#>)
  or
req.responseJSON(completionHandler: <#T##(DataResponse<Any>) -> Void#>)
-----------------------
let req = Alamofire.request(url, method: .get, parameters: nil)
req.response?.statusCode
req.responseString(completionHandler: <#T##(DataResponse<String>) -> Void#>)
  or
req.responseJSON(completionHandler: <#T##(DataResponse<Any>) -> Void#>)
-----------------------
import Foundation
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)
        }
    }
}
-----------------------
import Foundation
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)
        }
    }
}
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
import Foundation
import Alamofire

class NetworkCall : NSObject{

    enum services :String{
        case posts = "posts"
    }
    var parameters = Parameters()
    var headers = HTTPHeaders()
    var method: HTTPMethod!
    var url :String! = "https://jsonplaceholder.typicode.com/"
    var encoding: ParameterEncoding! = JSONEncoding.default

    init(data: [String:Any],headers: [String:String] = [:],url :String?,service :services? = nil, method: HTTPMethod = .post, isJSONRequest: Bool = true){
        super.init()
        data.forEach{parameters.updateValue($0.value, forKey: $0.key)}
        headers.forEach({self.headers.add(name: $0.key, value: $0.value)})
        if url == nil, service != nil{
            self.url += service!.rawValue
        }else{
            self.url = url
        }
        if !isJSONRequest{
            encoding = URLEncoding.default
        }
        self.method = method
        print("Service: \(service?.rawValue ?? self.url ?? "") \n data: \(parameters)")
    }

    func executeQuery<T>(completion: @escaping (Result<T, Error>) -> Void) where T: Codable {
        AF.request(url,method: method,parameters: parameters,encoding: encoding, headers: headers).responseData(completionHandler: {response in
            switch response.result{
            case .success(let res):
                if let code = response.response?.statusCode{
                    switch code {
                    case 200...299:
                        do {
                            completion(.success(try JSONDecoder().decode(T.self, from: res)))
                        } catch let error {
                            print(String(data: res, encoding: .utf8) ?? "nothing received")
                            completion(.failure(error))
                        }
                    default:
                     let error = NSError(domain: response.debugDescription, code: code, userInfo: response.response?.allHeaderFields as? [String: Any])
                        completion(.failure(error))
                    }
                }
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}
struct Post: Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}
let body: [String : Any] = ["title": "foo",
                                          "body": "bar",
                                          "userId": 1]
        NetworkCall(data: body, url: nil, service: .posts, method: .post).executeQuery(){
            (result: Result<Post,Error>) in
            switch result{
            case .success(let post):
                print(post)
            case .failure(let error):
                print(error)
            }
        }
Service: posts 
data: ["userId": 1, "body": "bar", "title": "foo"]
Post(userId: 1, id: 101, title: "foo", body: "bar")
Service: https://reqres.in/api/login 
 data: ["email": "peter@klaven"]
Error Domain=[Request]: POST https://reqres.in/api/login
[Request Body]: 
email=peter%40klaven
[Response]: 
[Status Code]: 400
[Headers]:
Access-Control-Allow-Origin: *
Content-Length: 28
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Feb 2020 05:41:26 GMT
Etag: W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q"
Server: cloudflare
Via: 1.1 vegur
cf-cache-status: DYNAMIC
cf-ray: 56c011c8ded2bb9a-LHR
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-powered-by: Express
[Response Body]: 
{"error":"Missing password"}
[Data]: 28 bytes
[Network Duration]: 2.2678009271621704s
[Serialization Duration]: 9.298324584960938e-05s
[Result]: success(28 bytes) Code=400 "(null)" UserInfo={cf-ray=56c011c8ded2bb9a-LHR, Access-Control-Allow-Origin=*, Date=Fri, 28 Feb 2020 05:41:26 GMT, expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct", Server=cloudflare, Etag=W/"1c-NmpazMScs9tOqR7eDEesn+pqC9Q", x-powered-by=Express, Content-Type=application/json; charset=utf-8, Content-Length=28, Via=1.1 vegur, cf-cache-status=DYNAMIC}
Service: https://httpbin.org/post 
 data: ["username": "sahil.manchanda2@gmail.com"]
{
  "args": {}, 
  "data": "{\"username\":\"sahil.manchanda2@gmail.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "br;q=1.0, gzip;q=0.9, deflate;q=0.8", 
    "Accept-Language": "en;q=1.0", 
    "Content-Length": "41", 
    "Content-Type": "application/json", 
    "Custom-Header-Key": "custom-header-value", 
    "Host": "httpbin.org", 
    "User-Agent": "NetworkCall/1.0 (sahil.NetworkCall; build:1; iOS 13.2.2) Alamofire/5.0.2", 
    "X-Amzn-Trace-Id": "Root=1-5e58a94f-fab2f24472d063f4991e2cb8"
  }, 
  "json": {
    "username": "sahil.manchanda2@gmail.com"
  }, 
  "origin": "182.77.56.154", 
  "url": "https://httpbin.org/post"
}

typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })
-----------------------
 typealias Closure<T> = (T)->()
 typealias JSON = [String: Any]
extension JSONDecoder{
func decode<T : Decodable>(_ model : T.Type,
                           result : @escaping Closure<T>) ->Closure<Data>{
    return { data in
        if let value = try? self.decode(model.self, from: data){
            result(value)
        }
    }
}
protocol APIResponseProtocol{
    func responseDecode<T: Decodable>(to modal : T.Type,
                              _ result : @escaping Closure<T>) -> APIResponseProtocol
    func responseJSON(_ result : @escaping Closure<JSON>) -> APIResponseProtocol
    func responseFailure(_ error :@escaping Closure<String>)
}
       let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 300 // seconds
        configuration.timeoutIntervalForResource = 500
        alamofireManager = Alamofire.SessionManager(configuration: configuration)

  func getRequest(forAPI api: String, params: JSON) -> APIResponseProtocol {
          let responseHandler = APIResponseHandler()
            var parameters = params
             parameters["token"] = preference.string(forKey: USER_ACCESS_TOKEN)
          alamofireManager.request(api,
                          method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: nil)
              .responseJSON { (response) in
                  print("Å api : ",response.request?.url ?? ("\(api)\(params)"))


                  switch response.result{
                  case .success(let value):
                      let json = value as! JSON
                      let error = json.string("error")
                      guard error.isEmpty else{

                          responseHandler.handleSuccess(value: value,data: response.data ?? Data())
                  case .failure(let error):
                      responseHandler.handleFailure(value: error.localizedDescription)
                  }
          }


          return responseHandler
      }
init(){
}
var jsonSeq : Closure<JSON>?
var dataSeq : Closure<Data>?
var errorSeq : Closure<String>?

func responseDecode<T>(to modal: T.Type, _ result: @escaping Closure<T>) -> APIResponseProtocol where T : Decodable {

    let decoder = JSONDecoder()
    self.dataSeq =  decoder.decode(modal, result: result)
    return self
}

func responseJSON(_ result: @escaping Closure<JSON>) -> APIResponseProtocol {
    self.jsonSeq = result
    return self
}
func responseFailure(_ error: @escaping Closure<String>) {
    self.errorSeq = error

  }




func handleSuccess(value : Any,data : Data){
    if let jsonEscaping = self.jsonSeq{
        jsonEscaping(value as! JSON)
    }
    if let dataEscaping = dataSeq{
        dataEscaping(data)

    }
}
func handleFailure(value : String){
    self.errorSeq?(value)
 }
self?.apiInteractor?
        .getRequest(forAPI: "https://maps.googleapis.com/maps/api/directions/json",
                    params: [
                        "origin" : "\(pickUpLatitude),\(pickUpLongitude)",
                        "destination" :"\(dropLatitude),\(dropLongitude)",
                        "mode" : "driving",
                        "units" : "metric",
                        "sensor" : "true",
                        "key" : "\(UserDefaults.value(for: .google_api_key) ?? "")"
        ])
        .responseDecode(to: GoogleGeocode.self, { [weak self] (googleGecode) in
            guard let welf = self,
                let route = googleGecode.routes.first,
                let leg = route.legs.first else{return}
            welf.tripDetailModel?.arrivalFromGoogle = leg.duration.text ?? ""
            welf.drawRoute(forRoute: route)
            welf.calculateETA()
        })
        .responseJSON({ (json) in
            debugPrint(json.description)
        })
        .responseFailure({ (error) in
            debug(print: error)
        })

Ionic app not opening(Crashing) in android device

copy iconCopydownload iconDownload
ionic cordova platform remove android
ionic cordova platform add android
-----------------------
ionic cordova platform remove android

React is unable to react property path of undefined

copy iconCopydownload iconDownload
//Imports
import HOC from 'path/to/my/hoc';

//...code

const MyHoc = HOC(DashboardContainer);

//Main class
class AppEntry extends React.Component {

//...code

// In the render method take advantage of render prop
render() {
  return (
    //...code
    <Route exact path="/my-path" render={(props) => <MyHoc {...props} />} />

use Android Native code (JAVA) in NativeScript

copy iconCopydownload iconDownload
import { Injectable } from '@angular/core';
import { ad as androidUtilities } from 'tns-core-modules/utils/utils';
import { AppUpdateAvailability } from '~/app/models/interfaces/app-update-availability.interface';
declare const com: any;

@Injectable({
  providedIn: 'root'
})
export class AppUpdateService {

  constructor() {
  }

  public checkForUpdate(): Promise<AppUpdateAvailability> {
    return new Promise((res, rej) => {
      try {
        const context = androidUtilities.getApplicationContext();
        const appUpdateManager = com.google.android.play.core.appupdate.AppUpdateManagerFactory.create(context);
        const appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
        appUpdateInfoTask.addOnSuccessListener(new com.google.android.play.core.tasks.OnSuccessListener({
          onSuccess: function (AppUpdateInfo: any) {
            const UpdateAvailability = com.google.android.play.core.install.model.UpdateAvailability;
            switch (AppUpdateInfo.updateAvailability()) {
              case UpdateAvailability.UNKNOWN:
                res(AppUpdateAvailability.Unknown);
                break;
              case UpdateAvailability.UPDATE_NOT_AVAILABLE:
                res(AppUpdateAvailability.UpdateNotAvailable);
                break;
              case UpdateAvailability.UPDATE_AVAILABLE:
                res(AppUpdateAvailability.UpdateAvailable);
                break;
              case UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS:
                res(AppUpdateAvailability.DeveloperTriggeredUpdateInProgress);
                break;
              default:
                rej('App update : Something went wrong!');
                break;
            }
          }
        }));
      } catch (err) {
        rej('Err in checkForUpdate() : Code error');
      }
    });

  }



}

Android error while receiving data from server

copy iconCopydownload iconDownload
btnCheckUpdates.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        { 
           new YourTask().execute();
        }
    });
private class YourTask extends AsyncTask<String, String,String> {
     protected String doInBackground(String... urls) {

         // put here your network operation method
           GetVersionFromServer(BuildVersionPath)

        return null;
     }

 }
-----------------------
btnCheckUpdates.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        { 
           new YourTask().execute();
        }
    });
private class YourTask extends AsyncTask<String, String,String> {
     protected String doInBackground(String... urls) {

         // put here your network operation method
           GetVersionFromServer(BuildVersionPath)

        return null;
     }

 }

Powershell Invoke-Expressions pauses

copy iconCopydownload iconDownload
#Invoke-expression $forceinstall
Invoke-Expression "force_install_dirC:\download\steam"
#Invoke-expression $appupdate
Invoke-Expression "app_update 258550"
Invoke-Expression "steamcmd +login anonymous +force_install_dir C:\download\steam +app_update 258550 +quit"
-----------------------
#Invoke-expression $forceinstall
Invoke-Expression "force_install_dirC:\download\steam"
#Invoke-expression $appupdate
Invoke-Expression "app_update 258550"
Invoke-Expression "steamcmd +login anonymous +force_install_dir C:\download\steam +app_update 258550 +quit"

window is full on App launch with GridView

copy iconCopydownload iconDownload
public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private ArrayList<String> mSingleItemLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_single_item);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }

    private void setDummyData() {
        for (int i = 0; i <= 1000; i++)
            mSingleItemLists.add("item" + i);
        SingleListItemAdapter singleListItemAdapter = new SingleListItemAdapter(mSingleItemLists);
        mRecyclerView.setAdapter(singleListItemAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setDummyData();
    }

    class SingleListItemAdapter extends RecyclerView.Adapter<SingleListItemAdapter.SingleListItemHolder> {
        private ArrayList<String> mSingleItemLists;

        private SingleListItemAdapter(ArrayList<String> singleItemLists) {
            mSingleItemLists = singleItemLists;
        }

        @Override
        public SingleListItemAdapter.SingleListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflatedView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.row_recyclerview, parent, false);
            return new SingleListItemHolder(inflatedView);
        }

        @Override
        public void onBindViewHolder(SingleListItemAdapter.SingleListItemHolder holder, int position) {
            holder.mItemDate.setText(mSingleItemLists.get(position));
            holder.mItemImageView.setImageResource(R.mipmap.ic_launcher_round);
        }

        @Override
        public int getItemCount() {
            return mSingleItemLists.size();
        }

        class SingleListItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            private TextView mItemDate;
            private ImageView mItemImageView;

            SingleListItemHolder(View v) {
                super(v);
                mItemDate = (TextView) v.findViewById(R.id.textview_recycler_list_item);
                mItemImageView = (ImageView) v.findViewById(R.id.imageview_icon);
                v.setOnClickListener(this);
                this.setIsRecyclable(false);
            }

            @Override
            public void onClick(View v) {
                //do your stuff
                notifyDataSetChanged();
            }
        }
    }

}
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_single_item"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:scrollbars="vertical" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview_recycler_list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="16dp"
        android:text="jeadfss"
        android:textColor="#000" />

    <ImageView
        android:id="@+id/imageview_icon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
-----------------------
public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private ArrayList<String> mSingleItemLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_single_item);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }

    private void setDummyData() {
        for (int i = 0; i <= 1000; i++)
            mSingleItemLists.add("item" + i);
        SingleListItemAdapter singleListItemAdapter = new SingleListItemAdapter(mSingleItemLists);
        mRecyclerView.setAdapter(singleListItemAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setDummyData();
    }

    class SingleListItemAdapter extends RecyclerView.Adapter<SingleListItemAdapter.SingleListItemHolder> {
        private ArrayList<String> mSingleItemLists;

        private SingleListItemAdapter(ArrayList<String> singleItemLists) {
            mSingleItemLists = singleItemLists;
        }

        @Override
        public SingleListItemAdapter.SingleListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflatedView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.row_recyclerview, parent, false);
            return new SingleListItemHolder(inflatedView);
        }

        @Override
        public void onBindViewHolder(SingleListItemAdapter.SingleListItemHolder holder, int position) {
            holder.mItemDate.setText(mSingleItemLists.get(position));
            holder.mItemImageView.setImageResource(R.mipmap.ic_launcher_round);
        }

        @Override
        public int getItemCount() {
            return mSingleItemLists.size();
        }

        class SingleListItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            private TextView mItemDate;
            private ImageView mItemImageView;

            SingleListItemHolder(View v) {
                super(v);
                mItemDate = (TextView) v.findViewById(R.id.textview_recycler_list_item);
                mItemImageView = (ImageView) v.findViewById(R.id.imageview_icon);
                v.setOnClickListener(this);
                this.setIsRecyclable(false);
            }

            @Override
            public void onClick(View v) {
                //do your stuff
                notifyDataSetChanged();
            }
        }
    }

}
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_single_item"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:scrollbars="vertical" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview_recycler_list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="16dp"
        android:text="jeadfss"
        android:textColor="#000" />

    <ImageView
        android:id="@+id/imageview_icon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
-----------------------
public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private ArrayList<String> mSingleItemLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_single_item);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }

    private void setDummyData() {
        for (int i = 0; i <= 1000; i++)
            mSingleItemLists.add("item" + i);
        SingleListItemAdapter singleListItemAdapter = new SingleListItemAdapter(mSingleItemLists);
        mRecyclerView.setAdapter(singleListItemAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setDummyData();
    }

    class SingleListItemAdapter extends RecyclerView.Adapter<SingleListItemAdapter.SingleListItemHolder> {
        private ArrayList<String> mSingleItemLists;

        private SingleListItemAdapter(ArrayList<String> singleItemLists) {
            mSingleItemLists = singleItemLists;
        }

        @Override
        public SingleListItemAdapter.SingleListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflatedView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.row_recyclerview, parent, false);
            return new SingleListItemHolder(inflatedView);
        }

        @Override
        public void onBindViewHolder(SingleListItemAdapter.SingleListItemHolder holder, int position) {
            holder.mItemDate.setText(mSingleItemLists.get(position));
            holder.mItemImageView.setImageResource(R.mipmap.ic_launcher_round);
        }

        @Override
        public int getItemCount() {
            return mSingleItemLists.size();
        }

        class SingleListItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            private TextView mItemDate;
            private ImageView mItemImageView;

            SingleListItemHolder(View v) {
                super(v);
                mItemDate = (TextView) v.findViewById(R.id.textview_recycler_list_item);
                mItemImageView = (ImageView) v.findViewById(R.id.imageview_icon);
                v.setOnClickListener(this);
                this.setIsRecyclable(false);
            }

            @Override
            public void onClick(View v) {
                //do your stuff
                notifyDataSetChanged();
            }
        }
    }

}
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_single_item"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:scrollbars="vertical" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview_recycler_list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="16dp"
        android:text="jeadfss"
        android:textColor="#000" />

    <ImageView
        android:id="@+id/imageview_icon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

How can I create an instance of a class used for data management in a Xamarin application?

copy iconCopydownload iconDownload
public class DataManager
{
    static readonly Lazy<DataManager> _instanceHolder = 
                new Lazy<DataManager>(() => new DataManager());

    ...

    //private constructor to prevent multiple instances of DataManager
    private DataManager()
    {
        ...
    }

    public static DataManager Instance => _instanceHolder.Value;

    ...
}

public partial class App : Application
{
    public App()
    {
        DataManager.Instance.appUpdated = "Feb 1, 2017";
        DataManager.Instance.appVersion = "0.1";
        InitializeComponent();
        MainPage = ..
    }

    protected override void OnStart()
    {
        DataManager.Instance.InitData();
    }
}

Community Discussions

Trending Discussions on AppUpdate
  • Can you pass a link to the update availability checker to check if the in-app update function is working well?
  • removing item from ListView.builder Flutter
  • How to simulate onFailureListener & resultCode != Activity.RESULT_OK In App Updates?
  • Fatal Exception: java.lang.NullPointerException in release build
  • iOS create generic Alamofire request using swift
  • Ionic app not opening(Crashing) in android device
  • React is unable to react property path of undefined
  • use Android Native code (JAVA) in NativeScript
  • java.lang.reflect.InvocationTargetException while inappupdate android if retries
  • Ionic app unfortunately stopped on real android device
Trending Discussions on AppUpdate

QUESTION

Can you pass a link to the update availability checker to check if the in-app update function is working well?

Asked 2021-Apr-14 at 10:20

I'm trying to implement the in-app updates on a new App I just created on Android Studio for testing. The app is just a "hello world" but I implemented the in-app updates checker as it says in these two pages:

https://developer.android.com/guide/playcore/in-app-updates#kotlin

https://johncodeos.com/how-to-implement-in-app-updates-in-android-using-kotlin/

We're using Google play for work (or the actual name for a "private acces" play store) where we upload our business App's, and these Apps are only for employees to use in stores. But even so, this Apps have a link, same as normal ones (https://play.google.com/store/apps/details?id=country.company.appname.something)

I think I understand how it works (more or less) but before uploading the app I want to check directly with another app link if it works.

My question is if I can use one of this links of one of our Apps (on a phone with acces and already configured, of course) to check if the update availability checker works or if I can only use it on the new App I'm doing and hence I need to upload it and do all the process with this "test" App

I put here the code so you can see it. Some snackbars are just for tracing the flow of the code.

UpdateInApp.kt class:

package com.example.demoinappupdates

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.InstallState
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability

class UpdateInApp(activity: Activity) : InstallStateUpdatedListener {

    private var appUpdateManager: AppUpdateManager
    private val MY_REQUEST_CODE = 500
    private var parentActivity: Activity = activity

    private var currentType = AppUpdateType.FLEXIBLE

    init {
        appUpdateManager = AppUpdateManagerFactory.create(parentActivity)
        appUpdateManager.appUpdateInfo.addOnSuccessListener { info ->
            // Check if update is available

            Snackbar.make(
                    parentActivity.findViewById(R.id.activity_main_layout),
                    "Aquí, en el init, entra",
                    Snackbar.LENGTH_INDEFINITE).show()

            if (info.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) { // UPDATE IS AVAILABLE
                if (info.updatePriority() == 5) { // Priority: 5 (Immediate update flow)
                    if (info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                        startUpdate(info, AppUpdateType.IMMEDIATE)
                    }
                } else if (info.updatePriority() == 4) { // Priority: 4
                    val clientVersionStalenessDays = info.clientVersionStalenessDays()
                    if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 5 && info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                        // Trigger IMMEDIATE flow
                        startUpdate(info, AppUpdateType.IMMEDIATE)
                    } else if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 3 && info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                        // Trigger FLEXIBLE flow
                        startUpdate(info, AppUpdateType.FLEXIBLE)
                    }
                } else if (info.updatePriority() == 3) { // Priority: 3
                    val clientVersionStalenessDays = info.clientVersionStalenessDays()
                    if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 30 && info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                        // Trigger IMMEDIATE flow
                        startUpdate(info, AppUpdateType.IMMEDIATE)
                    } else if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 15 && info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                        // Trigger FLEXIBLE flow
                        startUpdate(info, AppUpdateType.FLEXIBLE)
                    }
                } else if (info.updatePriority() == 2) { // Priority: 2
                    val clientVersionStalenessDays = info.clientVersionStalenessDays()
                    if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 90 && info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                        // Trigger IMMEDIATE flow
                        startUpdate(info, AppUpdateType.IMMEDIATE)
                    } else if (clientVersionStalenessDays != null && clientVersionStalenessDays >= 30 && info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
                        // Trigger FLEXIBLE flow
                        startUpdate(info, AppUpdateType.FLEXIBLE)
                    }
                } else if (info.updatePriority() == 1) { // Priority: 1
                    // Trigger FLEXIBLE flow
                    startUpdate(info, AppUpdateType.FLEXIBLE)
                } else { // Priority: 0
                    // Do not show in-app update
                }
            } else {
                // UPDATE IS NOT AVAILABLE
               /* Snackbar.make(
                        parentActivity.findViewById(R.id.activity_main_layout),
                        "El Snakcbar de prueba",
                        Snackbar.LENGTH_INDEFINITE).show() */
            }
        }
        appUpdateManager.registerListener(this)
    }


    private fun startUpdate(info: AppUpdateInfo, type: Int) {
        appUpdateManager.startUpdateFlowForResult(info, type, parentActivity, MY_REQUEST_CODE)
        currentType = type

        /* Snackbar.make(
                parentActivity.findViewById(R.id.activity_main_layout),
                "startupdate entra",
                Snackbar.LENGTH_INDEFINITE).show() */
    }

    fun onResume() {
        Snackbar.make(
                parentActivity.findViewById(R.id.activity_main_layout),
                "El Snakcbar de onresume",
                Snackbar.LENGTH_INDEFINITE).setAction("ejej"){}.show()

        appUpdateManager.appUpdateInfo.addOnSuccessListener { info ->
            if (currentType == AppUpdateType.FLEXIBLE) {
                // If the update is downloaded but not installed, notify the user to complete the update.
                if (info.installStatus() == InstallStatus.DOWNLOADED)
                    flexibleUpdateDownloadCompleted()
            } else if (currentType == AppUpdateType.IMMEDIATE) {
                // for AppUpdateType.IMMEDIATE only, already executing updater
                if (info.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                    startUpdate(info, AppUpdateType.IMMEDIATE)
                }
            }
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == MY_REQUEST_CODE) {
            if (resultCode != AppCompatActivity.RESULT_OK) {
                // If the update is cancelled or fails, you can request to start the update again.
                Log.e("ERROR", "Update flow failed! Result code: $resultCode")
            }
        }
    }

    private fun flexibleUpdateDownloadCompleted() {
        Snackbar.make(
            parentActivity.findViewById(R.id.activity_main_layout),
            "An update has just been downloaded.",
            Snackbar.LENGTH_INDEFINITE
        ).apply {
            setAction("RESTART") { appUpdateManager.completeUpdate() }
            setActionTextColor(Color.WHITE)
            show()
        }
    }

    fun onDestroy() {
        appUpdateManager.unregisterListener(this)
    }

    override fun onStateUpdate(state: InstallState) {
        if (state.installStatus() == InstallStatus.DOWNLOADED) {
            flexibleUpdateDownloadCompleted()
        }
    }

}

MainActivity.kt class

package com.example.demoinappupdates

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    private lateinit var inAppUpdate: UpdateInApp

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        inAppUpdate = UpdateInApp(this)
       /* Snackbar.make(
            this.findViewById(R.id.activity_main_layout),
            "El Snakcbar de prueba",
            Snackbar.LENGTH_INDEFINITE).show()*/
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        inAppUpdate.onActivityResult(requestCode,resultCode, data)
    }

    override fun onResume() {
        super.onResume()
        inAppUpdate.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        inAppUpdate.onDestroy()
    }

}

ANSWER

Answered 2021-Apr-14 at 10:20

I think it's not possible, since what I'm trying to do could only be done changing the Bundle ID, and that would cause some compatibility issues based on more than just one app sharing the same one.

For the record, when I refer to the Bundle ID I mean applicationId on the build.gradle file.

Source https://stackoverflow.com/questions/66813381

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install AppUpdate

You can download it from GitHub.
You can use AppUpdate like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the AppUpdate component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.