Merge branch 'develop' into feature/sms_action

This commit is contained in:
Kevin G Christiano 2021-03-23 12:09:45 -04:00
commit 236eaa6eb3
10 changed files with 284 additions and 146 deletions

View File

@ -21,6 +21,7 @@
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
016CF36925FA6DD400B82A1F /* ClientParameterHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 016CF36825FA6DD400B82A1F /* ClientParameterHandler.swift */; };
016FF6EE259A4E6300F5E4AA /* ClientParameterModelProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 016FF6ED259A4E6300F5E4AA /* ClientParameterModelProtocol.swift */; };
016FF6F2259A4FCC00F5E4AA /* ClientParameterModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 016FF6F1259A4FCC00F5E4AA /* ClientParameterModel.swift */; };
016FF6F6259B9AED00F5E4AA /* ClientParameterRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 016FF6F5259B9AED00F5E4AA /* ClientParameterRegistry.swift */; };
@ -150,9 +151,11 @@
D2DEDCB923C6400600C44CC4 /* UnitInterval.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2DEDCB823C6400600C44CC4 /* UnitInterval.swift */; };
D2DEDCBB23C65BC300C44CC4 /* Percent.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2DEDCBA23C65BC300C44CC4 /* Percent.swift */; };
D2E1FAD92260C3E400AEFD8C /* DelegateObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2E1FAD82260C3E400AEFD8C /* DelegateObject.swift */; };
EA3B264C25FC0B7600008074 /* ModelHandlerProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA3B264B25FC0B7600008074 /* ModelHandlerProtocol.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
016CF36825FA6DD400B82A1F /* ClientParameterHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientParameterHandler.swift; sourceTree = "<group>"; };
016FF6ED259A4E6300F5E4AA /* ClientParameterModelProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientParameterModelProtocol.swift; sourceTree = "<group>"; };
016FF6F1259A4FCC00F5E4AA /* ClientParameterModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientParameterModel.swift; sourceTree = "<group>"; };
016FF6F5259B9AED00F5E4AA /* ClientParameterRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClientParameterRegistry.swift; sourceTree = "<group>"; };
@ -290,6 +293,7 @@
D2DEDCB823C6400600C44CC4 /* UnitInterval.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnitInterval.swift; sourceTree = "<group>"; };
D2DEDCBA23C65BC300C44CC4 /* Percent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Percent.swift; sourceTree = "<group>"; };
D2E1FAD82260C3E400AEFD8C /* DelegateObject.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelegateObject.swift; sourceTree = "<group>"; };
EA3B264B25FC0B7600008074 /* ModelHandlerProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelHandlerProtocol.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -311,6 +315,7 @@
016FF6ED259A4E6300F5E4AA /* ClientParameterModelProtocol.swift */,
016FF6F1259A4FCC00F5E4AA /* ClientParameterModel.swift */,
016FF6F5259B9AED00F5E4AA /* ClientParameterRegistry.swift */,
016CF36825FA6DD400B82A1F /* ClientParameterHandler.swift */,
01934FE625A4FFC2003DCD67 /* ClientParameterActionProtocol.swift */,
);
path = "Client Parameters";
@ -406,6 +411,7 @@
946EE1A8237B5C650036751F /* Model */ = {
isa = PBXGroup;
children = (
EA3B264B25FC0B7600008074 /* ModelHandlerProtocol.swift */,
946EE1A2237B59C30036751F /* ModelProtocol.swift */,
946EE1A6237B5B1C0036751F /* ModelRegistry.swift */,
);
@ -860,6 +866,7 @@
AFBB96351FBA34310008D868 /* MVMCoreErrorConstants.m in Sources */,
AF43A5881FBB67D6008E9347 /* MVMCoreActionUtility.m in Sources */,
AFED77A61FCCA29400BAE689 /* MVMCoreViewControllerStoryBoardMappingObject.m in Sources */,
016CF36925FA6DD400B82A1F /* ClientParameterHandler.swift in Sources */,
AF43A57C1FBA5E6A008E9347 /* MVMCoreHardcodedStringsConstants.m in Sources */,
0AFF597A23FC6E60005C24E8 /* ActionShareModel.swift in Sources */,
AFEEE81F1FCDF3CA00B5EDD0 /* MVMCoreLoggingHandler.m in Sources */,
@ -872,6 +879,7 @@
94C014D924212360005811A9 /* ActionSettingModel.swift in Sources */,
D2DEDCB723C63F3B00C44CC4 /* Clamping.swift in Sources */,
01DF561421F90ADC00CC099B /* Dictionary+MFConvenience.swift in Sources */,
EA3B264C25FC0B7600008074 /* ModelHandlerProtocol.swift in Sources */,
AFBB96B11FBA3B590008D868 /* MVMCoreDispatchUtility.m in Sources */,
946EE1A3237B59C30036751F /* ModelProtocol.swift in Sources */,
AFEA17A9209B6A1C00BC6740 /* MVMCoreBlockOperation.m in Sources */,

View File

@ -32,7 +32,7 @@ extern NSString * _Nonnull const KeyActionTypeOpen;
- (void)synchronouslyHandleAction:(nullable NSString *)actionType actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject;
/// Iterates through the clientParameters list. Gets values from the individual handlers and attaches the parameters to extraParameters.
- (void)setClientParameter:(nullable NSDictionary *)actionInformation completionHandler:(nonnull void (^)(NSDictionary * _Nullable jsonDictionary))completionHandler;
- (void)getClientParameter:(nullable NSDictionary *)clientParametersMap requestParameters:(nullable NSDictionary *)requestParameters showLoadingOverlay:(BOOL)showLoadingOverlay completionHandler:(nonnull void (^)(NSDictionary * _Nullable jsonDictionary))completionHandler;
#pragma mark - Actions
/// by default, returns the original RequestParameter that passed in. Can be overriden for some generic updates to the RequestParameter before handle open page action gets called.
@ -100,7 +100,7 @@ extern NSString * _Nonnull const KeyActionTypeOpen;
+ (void)defaultLogAction:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject;
/// Sends the request to the load handler.
+ (void)defaultHandleOpenPageForRequestParameters:(nonnull MVMCoreRequestParameters *)requestParameters additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject;
+ (void)defaultHandleOpenPageForRequestParameters:(nonnull MVMCoreRequestParameters *)requestParameters actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject;
/// By default, throws an error, calling defaultHandleActionError.
+ (void)defaultHandleUnknownActionType:(nullable NSString *)actionType actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject;

View File

@ -96,50 +96,45 @@ NSString * const KeyActionTypeOpen = @"openPage";
}
}
- (void)setClientParameter:(nullable NSDictionary *)actionInformation completionHandler:(nonnull void (^)(NSDictionary * _Nullable jsonDictionary))completionHandler {
- (void)getClientParameter:(nullable NSDictionary *)clientParametersMap requestParameters:(nullable NSDictionary *)requestParameters showLoadingOverlay:(BOOL)showLoadingOverlay completionHandler:(nonnull void (^)(NSDictionary * _Nullable parameters))completionHandler {
NSDictionary *clientParametersMap = [actionInformation dict:KeyClientParameters];
if (!clientParametersMap) {
completionHandler(actionInformation);
completionHandler(nil);
return;
}
BOOL isBackgroudRequest = [actionInformation boolForKey:@"background"];
if (!isBackgroudRequest) {
if (showLoadingOverlay) {
[[MVMCoreLoadingOverlayHandler sharedLoadingOverlay] startLoading];
}
void (^stopLoadingOverlay)(void) = ^(void) {
if (!isBackgroudRequest) {
if (showLoadingOverlay) {
[[MVMCoreLoadingOverlayHandler sharedLoadingOverlay] stopLoading:true];
}
};
NSError *error = nil;
[MVMCoreLoggingHandler logDebugMessageWithDelegate:@"Fetching client parameters"];
[[[MVMCoreObject sharedInstance] clientParameterRegistry] getParametersWith:clientParametersMap
ClientParameterHandler *clientParameterHandler = [[ClientParameterHandler alloc] init];
[clientParameterHandler getParametersWith:clientParametersMap
requestParameters:requestParameters
error:&error
completionHandler:^(NSDictionary<NSString *,id> * _Nullable clientParameters) {
[MVMCoreLoggingHandler logDebugMessageWithDelegate:@"Finshed fetching client parameters"];
if (clientParameters) {
NSMutableDictionary *actionWithClientParameters = [actionInformation mutableCopy];
NSMutableDictionary *extraParameters = [clientParameters mutableCopy];
[extraParameters addEntriesFromDictionary:[actionWithClientParameters dictionaryForKey:KeyExtraParameters]];
actionWithClientParameters[KeyExtraParameters] = extraParameters;
stopLoadingOverlay();
completionHandler(actionWithClientParameters);
completionHandler(clientParameters);
} else {
[MVMCoreLoggingHandler logDebugMessageWithDelegate:@"No client parameters"];
stopLoadingOverlay();
completionHandler(actionInformation);
completionHandler(nil);
}
}];
if (error) {
stopLoadingOverlay();
completionHandler(actionInformation);
completionHandler(nil);
[MVMCoreLoggingHandler addErrorToLog:[MVMCoreErrorObject createErrorObjectForNSError:error location:@"MVMCoreActionHandler->setClientParameter"]];
}
}
@ -171,20 +166,17 @@ NSString * const KeyActionTypeOpen = @"openPage";
return;
}
__weak typeof(self) weakSelf = self;
void (^performAction)(NSDictionary*) = ^(NSDictionary* actionMap) {
MVMCoreRequestParameters *requestParameters = [[MVMCoreRequestParameters alloc] initWithActionMap:actionMap];
[weakSelf updateRequestParametersBeforeHandleOpenPageAction:requestParameters callBack:^(MVMCoreRequestParameters * _Nonnull requestParameters) {
if ([delegateObject.actionDelegate respondsToSelector:@selector(handleOpenPageForRequestParameters:actionInformation:additionalData:)]) {
[delegateObject.actionDelegate handleOpenPageForRequestParameters:requestParameters actionInformation:actionInformation additionalData:additionalData];
} else {
[MVMCoreActionHandler defaultHandleOpenPageForRequestParameters:requestParameters additionalData:additionalData delegateObject:delegateObject];
}
}];
};
[self setClientParameter:actionInformation completionHandler:performAction];
MVMCoreRequestParameters *requestParameters = [[MVMCoreRequestParameters alloc] initWithActionMap:actionInformation];
[self updateRequestParametersBeforeHandleOpenPageAction:requestParameters callBack:^(MVMCoreRequestParameters * _Nonnull requestParameters) {
if ([delegateObject.actionDelegate respondsToSelector:@selector(handleOpenPageForRequestParameters:actionInformation:additionalData:)]) {
[delegateObject.actionDelegate handleOpenPageForRequestParameters:requestParameters actionInformation:actionInformation additionalData:additionalData];
} else {
[MVMCoreActionHandler defaultHandleOpenPageForRequestParameters:requestParameters
actionInformation:actionInformation
additionalData:additionalData
delegateObject:delegateObject];
}
}];
}
- (void)shareAction:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {
@ -292,7 +284,10 @@ NSString * const KeyActionTypeOpen = @"openPage";
if ([delegateObject.actionDelegate respondsToSelector:@selector(handleOpenPageForRequestParameters:actionInformation:additionalData:)]) {
[delegateObject.actionDelegate handleOpenPageForRequestParameters:requestParameters actionInformation:actionInformation additionalData:dataForPage];
} else {
[MVMCoreActionHandler defaultHandleOpenPageForRequestParameters:requestParameters additionalData:additionalData delegateObject:delegateObject];
[MVMCoreActionHandler defaultHandleOpenPageForRequestParameters:requestParameters
actionInformation:actionInformation
additionalData:additionalData
delegateObject:delegateObject];
}
}];
}];
@ -354,26 +349,35 @@ NSString * const KeyActionTypeOpen = @"openPage";
- (void)linkAwayAction:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {
__weak typeof(self) weakSelf = self;
void (^performAction)(NSDictionary*) = ^(NSDictionary* actionMap) {
void (^performAction)(NSDictionary*) = ^(NSDictionary* extraParamters) {
NSMutableDictionary *actionWithClientParameters = [actionInformation mutableCopy];
NSMutableDictionary *extraParametersT = [extraParamters mutableCopy];
[extraParametersT addEntriesFromDictionary:[actionWithClientParameters dictionaryForKey:KeyExtraParameters]];
actionWithClientParameters[KeyExtraParameters] = extraParametersT;
// Gets the app url
NSURL *appURL = nil;
NSString *appURLString = [actionMap string:KeyLinkAwayAppURL];
NSString *appURLString = [actionWithClientParameters string:KeyLinkAwayAppURL];
if (appURLString.length > 0) {
appURL = [NSURL URLWithString:appURLString];
}
// Gets the browser url
NSURL *otherURL = nil;
NSString *otherURLString = [actionMap string:KeyLinkAwayURL];
NSString *otherURLString = [actionWithClientParameters string:KeyLinkAwayURL];
if (otherURLString.length > 0) {
otherURL = [NSURL URLWithString:otherURLString];
}
// Provide the URL and App URL to be modified if needed by a subclass or delegate.
[weakSelf prepareLinkAwayWithURL:otherURL appURL:appURL actionInformation:actionMap additionalData:additionalData delegateObject:delegateObject];
[weakSelf prepareLinkAwayWithURL:otherURL appURL:appURL actionInformation:actionWithClientParameters additionalData:additionalData delegateObject:delegateObject];
};
[self setClientParameter:actionInformation completionHandler:performAction];
[self getClientParameter:[actionInformation dict:KeyClientParameters]
requestParameters:nil
showLoadingOverlay:true
completionHandler:performAction];
}
- (void)prepareLinkAwayWithURL:(nullable NSURL *)url appURL:(nullable NSURL *)appURL actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {
@ -432,8 +436,20 @@ NSString * const KeyActionTypeOpen = @"openPage";
// Currently no default log action but this will eventually be server driven.
}
+ (void)defaultHandleOpenPageForRequestParameters:(nonnull MVMCoreRequestParameters *)requestParameters additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {
[[MVMCoreLoadHandler sharedGlobal] loadRequest:requestParameters dataForPage:additionalData delegateObject:delegateObject];
+ (void)defaultHandleOpenPageForRequestParameters:(nonnull MVMCoreRequestParameters *)requestParameters actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {
NSDictionary *clientParamters = [actionInformation dict:KeyClientParameters];
if (clientParamters) {
[[MVMCoreActionHandler sharedActionHandler] getClientParameter:clientParamters
requestParameters: requestParameters.parameters
showLoadingOverlay: !requestParameters.backgroundRequest
completionHandler: ^(NSDictionary * _Nullable jsonDictionary) {
[requestParameters addRequestParameters:jsonDictionary];
[[MVMCoreLoadHandler sharedGlobal] loadRequest:requestParameters dataForPage:additionalData delegateObject:delegateObject];
}];
} else {
[[MVMCoreLoadHandler sharedGlobal] loadRequest:requestParameters dataForPage:additionalData delegateObject:delegateObject];
}
}
+ (void)defaultHandleUnknownActionType:(nullable NSString *)actionType actionInformation:(nullable NSDictionary *)actionInformation additionalData:(nullable NSDictionary *)additionalData delegateObject:(nullable DelegateObject *)delegateObject {

View File

@ -0,0 +1,108 @@
//
// ClientParameterHandler.swift
// MVMCore
//
// Created by Suresh, Kamlesh on 3/11/21.
// Copyright © 2021 myverizon. All rights reserved.
//
import Foundation
@objcMembers open class ClientParameterHandler: NSObject {
var parameterHandlerList: [ClientParameterProtocol] = []
let parametersWorkQueue = DispatchQueue(label: "com.mva.clientparameter")
let group = DispatchGroup()
open func createParametersHandler(_ clientParameterModel: ClientParameterModelProtocol) -> ClientParameterProtocol? {
guard let parameterType = MVMCoreObject.sharedInstance()?.clientParameterRegistry?.mapping[clientParameterModel.type] else { return nil }
return parameterType.init(clientParameterModel)
}
func getClientParameterModel(_ clientParameters: [String: Any]) throws -> ClientParameterModel? {
let data = try JSONSerialization.data(withJSONObject: clientParameters)
return try JSONDecoder().decode(ClientParameterModel.self, from: data)
}
/// Sample clientParameters
///{
/// "timeout": 30,
/// "list": [
/// {
/// "type": "currentLocation",
/// "inputParameters": {
/// "accuracy": 10,
/// "timeThreshold": 600
/// }
/// }
/// ]
///}
/// completionHandler can return flat dictinary or a map. It depends on the paramters handler
open func getParameters(with clientParameters: [String: Any], requestParameters: [String: Any], completionHandler:@escaping ([String: Any]?) -> ()) throws {
guard let clientParameterModel = try getClientParameterModel(clientParameters) else {
completionHandler(nil)
return
}
let timeout = clientParameterModel.timeout ?? 30.0
// Dispatch setup on queue to ensure setup is complete before completion callbacks.
// Don't use [weak self]. Object is deallocated in the dispatch queue.
parametersWorkQueue.async(group: group, qos: .userInitiated) {
// Create the handler list so that same object can be used when merging. Merging needs default value in case of timeout
for parameterModel in clientParameterModel.list {
if let parameterHandler = self.createParametersHandler(parameterModel) {
self.parameterHandlerList.append(parameterHandler)
}
}
var returnedList = [[String: AnyHashable]?](repeating: nil, count: self.parameterHandlerList.count)
var mergedParametersList: [String: AnyHashable] {
var parametersList: [String: AnyHashable] = [:]
for (index, item) in returnedList.enumerated() {
let parameter = item ?? self.parameterHandlerList[index].valueOnTimeout()
parametersList = parametersList.merging(parameter) { (_, new) in new }
}
return parametersList
}
// Setup completion handlers. Barriered to ensure one happens after the other.
var complete = false
let timeoutWorkItem = DispatchWorkItem(qos: .userInitiated) {
completionHandler(mergedParametersList);
complete = true
}
let completionWorkItem = DispatchWorkItem(qos: .userInitiated) {
timeoutWorkItem.cancel()
if !complete { // In the case of firing after timeout.
completionHandler(mergedParametersList);
complete = true
}
}
// Setup timeout.
self.parametersWorkQueue.asyncAfter(deadline: .now() + .seconds(Int(timeout)), execute: timeoutWorkItem)
// Setup the parameter execution.
for (index, parameterHandler) in self.parameterHandlerList.enumerated() {
self.group.enter()
parameterHandler.fetchClientParameters(requestParameters: requestParameters,
timingOutIn: timeout) { (receivedParameter) in
// Queue the results for merge.
self.parametersWorkQueue.async {
returnedList[index] = receivedParameter
self.group.leave() // Leaving is only done after setup (barriered).
}
}
}
// Callback when all parameters have been merged.
self.group.notify(queue: self.parametersWorkQueue, work: completionWorkItem);
}
}
}

View File

@ -9,7 +9,33 @@
import Foundation
public protocol ClientParameterProtocol {
init()
static var name: String { get }
func fetchClientParameters(for paramModel: ClientParameterModelProtocol, timingOutIn timeout: Double, completionHandler:@escaping (AnyHashable?) -> ())
init(_ clientParameterModel: ClientParameterModelProtocol)
var clientParameterModel: ClientParameterModelProtocol { get set }
func fetchClientParameters(requestParameters: [String: Any], timingOutIn timeout: Double, completionHandler:@escaping ([String: AnyHashable]?) -> ())
/// Default parameter for timeout scenarios. It will use the protocol extension method bydefault. Can override to send custom values.
func valueOnTimeout() -> [String: AnyHashable]
}
public extension ClientParameterProtocol {
func valueOnTimeout() -> [String: AnyHashable] {
return [Self.name: "failed_to_collect"]
}
/// The handler should call this method to pass the parameter back to the caller.
func returnParameters(_ isFlatMap: Bool, _ parameter: [String: AnyHashable]?, completionHandler: @escaping ([String: AnyHashable]?) -> ()) {
guard let parameter = parameter else {
return completionHandler(nil)
}
if isFlatMap {
completionHandler(parameter)
} else {
completionHandler([Self.name: parameter])
}
}
}

View File

@ -11,8 +11,7 @@ import Foundation
@objcMembers open class ClientParameterRegistry: NSObject {
private var mapping: [String: ClientParameterProtocol.Type] = [:]
var mapping: [String: ClientParameterProtocol.Type] = [:]
public override init() {
super.init()
@ -23,98 +22,11 @@ import Foundation
mapping[T.name] = handler
}
open func createParametersHandler(_ actionType: String) -> ClientParameterProtocol? {
guard let parameterType = mapping[actionType] else { return nil }
return parameterType.init()
}
static func getClientParameterModel(_ clientParameters: [String: Any]) throws -> ClientParameterModel? {
let data = try JSONSerialization.data(withJSONObject: clientParameters)
return try JSONDecoder().decode(ClientParameterModel.self, from: data)
}
/// Sample clientParameters
///{
/// "timeout": 30,
/// "list": [
/// {
/// "type": "currentLocation",
/// "inputParameters": {
/// "accuracy": 10,
/// "timeThreshold": 600
/// }
/// }
/// ]
///}
/// completionHandler can return flat dictinary or a map. It depends on the paramters handler
open func getParameters(with clientParameters: [String: Any], completionHandler:@escaping ([String: Any]?) -> ()) throws {
guard let clientParameterModel = try ClientParameterRegistry.getClientParameterModel(clientParameters) else {
completionHandler(nil)
return
}
var parametersList: [String: Any] = [:]
let timeout = clientParameterModel.timeout ?? 30.0
let parametersWorkQueue = DispatchQueue(label: "com.mva.clientparameter")
let group = DispatchGroup()
let defaultErrorString = "failed_to_collect."
// Dispatch setup on queue to ensure setup is complete before completion callbacks.
parametersWorkQueue.async(group: group, qos: .userInitiated) { [weak self] in
guard let self = self else { return }
// Setup completion handlers. Barriered to ensure one happens after the other.
var complete = false
let timeoutWorkItem = DispatchWorkItem(qos: .userInitiated) {
completionHandler(parametersList);
complete = true
}
let completionWorkItem = DispatchWorkItem(qos: .userInitiated) {
timeoutWorkItem.cancel()
if !complete { // In the case of firing after timeout.
completionHandler(parametersList);
complete = true
}
}
// Setup timeout.
parametersWorkQueue.asyncAfter(deadline: .now() + .seconds(Int(timeout)), execute: timeoutWorkItem)
// Setup the parameter execution.
for parameterModel in clientParameterModel.list {
// Setup default timeout / nil error. This will be replaced as parameters are collected.
parametersList[parameterModel.type] = ["error": defaultErrorString]
group.enter()
// Dispatch asynchronous injection.
self.getParameterFromHandler(parameterModel, before: timeout) { (receivedParameter) in
// Queue the results for merge.
parametersWorkQueue.async {
if let receivedParameter = receivedParameter {
parametersList[parameterModel.type] = receivedParameter
}
group.leave() // Leaving is only done after setup (barriered).
}
}
}
// Callback when all parameters have been merged.
group.notify(queue: parametersWorkQueue, work: completionWorkItem);
}
}
func getParameterFromHandler( _ parameterModel: ClientParameterModelProtocol, before timeout: Double, completionHandler:@escaping (AnyHashable?) -> ()) {
guard let parameterHandler = createParametersHandler(parameterModel.type) else {
return completionHandler(nil)
}
parameterHandler.fetchClientParameters(for: parameterModel, timingOutIn: timeout, completionHandler: completionHandler)
}
/// Add all registry here.
open func registerParameters() { }
/// Register Default Core Client Paramter Objects
public func register<T:ClientParameterProtocol, M: ModelProtocol>(handler: T.Type, for model: M.Type) throws {
public func register<T:ClientParameterProtocol, M: ModelProtocol>(handler: T.Type, for model: M.Type) throws {
try ModelRegistry.register(model)
register(handler)
}

View File

@ -0,0 +1,11 @@
//
// ModelViewProtocol.swift
// MVMCore
//
// Created by Matt Bruce on 3/12/21.
// Copyright © 2021 myverizon. All rights reserved.
//
import Foundation
public protocol ModelHandlerProtocol {}

View File

@ -7,7 +7,6 @@
// Copyright © 2019 myverizon. All rights reserved.
//
import Foundation
public struct ModelRegistry {
@ -25,24 +24,59 @@ public struct ModelRegistry {
var name: String
var codingKey: String
var instanceTypes: [String: ModelProtocol.Type] = [:]
var handlerTypes: [String: ModelHandlerProtocol.Type] = [:]
}
private static var categories: [String: Category] = [:]
/// Registers models for Atomic use.
public static func register<H: ModelHandlerProtocol, M: ModelProtocol>(handler: H.Type, for model: M.Type) throws {
//register the type
try self.register(model)
//get the key for the handler
let key = model.identifier
//get the category for the ModelProtocol
var category = getCategory(for: model)
// Check to ensure the Category/Container combination doesn't exist.
if category.handlerTypes[key] != nil {
throw ModelRegistry.Error.other(message: "ModelHandlerProtocol: \(String(describing: handler)) already exists in Category: \(category.name)")
} else {
category.handlerTypes[key] = handler
}
categories[category.name] = category
}
/// Registers models for Atomic use.
public static func register<M: ModelProtocol>(_ type: M.Type) throws {
var category = categories[M.categoryName] ?? Category(name: M.categoryName, codingKey: M.categoryCodingKey)
//get the category for the ModelProtocol
var category = getCategory(for: type)
// Check to ensure the Category/Type combination doesn't exist.
if category.instanceTypes[M.identifier] != nil {
throw ModelRegistry.Error.other(message: "ModelProtocol: \(M.identifier) already exists in Category: \(M.categoryName)")
}
category.instanceTypes[M.identifier] = type
categories[M.categoryName] = category
}
public static func getHandler(_ model: ModelProtocol) -> ModelHandlerProtocol.Type? {
//get the modelType
let modelType = type(of: model)
//get the category for the ModelProtocol
guard let category = categories[modelType.categoryName] else { return nil }
//get the containerProtocol for this ModelProtocol you had registered
return category.handlerTypes[modelType.identifier]
}
private static func getCategory<M: ModelProtocol>(for type: M.Type) -> Category {
return categories[type.categoryName] ?? Category(name: type.categoryName, codingKey: type.categoryCodingKey)
}
private static func getCategory<T>(for type: T.Type) -> Category? {
// Temporary code till we find a better solution.
//if this is a protocol composotion, loop through each protocol for a category lookup

View File

@ -19,6 +19,15 @@
// Returns the hardcoded string from the string file.
+ (nullable NSString *)hardcodedStringWithKey:(nonnull NSString *)key;
// Returns the hardcoded string from the string file based on module.
+ (nullable NSString *)hardcodedStringWithKey:(nonnull NSString *)key bundle:(nullable NSBundle *)bundle;
// Return current system language
+ (nullable NSString *)getSystemLanguage;
// Return current preferred system language
+ (nullable NSString *)getPreferredAvailableLanguage;
// Returns true if the user's language is Spanish
+ (BOOL)userPrefersSpanish;

View File

@ -18,20 +18,34 @@
return [NSBundle bundleWithIdentifier:@"com.vzw.MVMCore"];
}
// Confirms that the preferred user language is for spanish users.
+ (BOOL)userPrefersSpanish {
// This should be enough for us to look at what the user prefers.
return [[[[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2] lowercaseString] isEqualToString:@"es"];
return [[[MVMCoreGetterUtility getPreferredAvailableLanguage] lowercaseString] hasPrefix:@"es"];
}
// Gets language code based on what the user prefers and the app provides.
+ (NSString *)getPreferredAvailableLanguage {
return [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
}
// Returns the preferred language set system wide.
+ (NSString *)getSystemLanguage {
return [[NSLocale preferredLanguages] objectAtIndex:0];
}
+ (nullable NSString *)hardcodedStringWithKey:(nonnull NSString *)key {
// Redirect key with relevant module.
return [MVMCoreGetterUtility hardcodedStringWithKey:key bundle:[MVMCoreGetterUtility bundleForMVMCore]];
}
+ (nullable NSString *)hardcodedStringWithKey:(nonnull NSString *)key bundle:(nullable NSBundle *)bundle {
// If the app language is not english... force load from the english file anyway.
if ([MVMCoreGetterUtility userPrefersSpanish]) {
return [[NSBundle bundleWithPath:[[MVMCoreGetterUtility bundleForMVMCore] pathForResource:@"es" ofType:@"lproj"]] localizedStringForKey:key value:@"" table:nil];
} else {
return [[NSBundle bundleWithPath:[[MVMCoreGetterUtility bundleForMVMCore] pathForResource:@"en" ofType:@"lproj"]] localizedStringForKey:key value:@"" table:nil];
}
NSString *languageCode = [MVMCoreGetterUtility userPrefersSpanish] ? @"es" : @"en";
return [[NSBundle bundleWithPath:[bundle pathForResource:languageCode ofType:@"lproj"]] localizedStringForKey:key value:@"" table:nil];
}
+ (nonnull UIColor *)getColorForHexString:(nonnull NSString *)hexString {