Configure Privacy Protocol - iOS

Keywords: Mobile network encoding

According to the new rules of Apple Privacy Protocol, all applications are required to include privacy protection protocols, so the following privacy protocol modules are added to App.

When App is installed for the first time, the Privacy Protocol module is called by default to display the relevant information once. When the user clicks the consent button, the module method is no longer executed.

Specific code s are as follows:

Statement (.h)

/*
 Privacy protocol
 */
#import <Foundation/Foundation.h>

@interface PrivacyAgreement : NSObject

+ (instancetype)shareInstance;

@end

2. Implementation (.m)

#import "PrivacyAgreement.h"

/** Getting Sandbox Document Path*/
#define kDocumentPath       [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
#define kKeyWindow          [UIApplication sharedApplication].keyWindow

#define SCREEN_WIDTH    ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT   ([UIScreen mainScreen].bounds.size.height)

#Define LocalName_Project Config@ "Project ConfigInfo.plist"//Local Storage Path Settings_File Name
#Define LocalPath_Project Config @ "Project/Project ConfigInfo/"//Local Storage Path Settings_File Path
#define PrivacyAgreementState  @"PrivacyAgreementState"

@interface PrivacyAgreement () <WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIButton *btnAgree;
@property (nonatomic, strong) WKWebView *webView;

@end

@implementation PrivacyAgreement

+ (instancetype)shareInstance {
    static PrivacyAgreement *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PrivacyAgreement alloc] init];
    });
    
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:[kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", LocalPath_ProjectConfig, LocalName_ProjectConfig]]]) {
                NSMutableDictionary *configInfo = [NSMutableDictionary dictionaryWithContentsOfFile:[kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", LocalPath_ProjectConfig, LocalName_ProjectConfig]]];
                if ([[configInfo objectForKey:@"PrivacyAgreementState"] isEqualToString:@"PrivacyAgreementState"]) {} else {
                    // Show Privacy AgreementState View
                    [self showPrivacyAgreementStateView];
                }
            }
            else {
                // Show Privacy AgreementState View
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self showPrivacyAgreementStateView];
                });
            }
        }];
    }
    
    return self;
}



/**
 Rendering Privacy Protocol View
 */
- (void)showPrivacyAgreementStateView {
    [kKeyWindow addSubview:self.backgroundView];
    [self webView];
    [self.backgroundView addSubview:self.btnAgree];
}



#pragma mark - ************************************************ UI
- (UIView *)backgroundView {
    if (!_backgroundView) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        view.backgroundColor = [UIColor whiteColor];
        view.userInteractionEnabled = YES;
        
        _backgroundView = view;
    }
    return _backgroundView;
}

/**
 WebView Set correlation
 
 It contains loading mode (local file & Network request)

 @return Current controls
 */
- (WKWebView *)webView {
    if (!_webView) {
        NSError *error;
        // Local url address settings
        NSURL *URLBase = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
        NSString *URLAgreement = [[NSBundle mainBundle] pathForResource:@"agreement" ofType:@"html"];
        NSString *html = [NSString stringWithContentsOfFile:URLAgreement
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
        
        WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
        webConfig.preferences = [[WKPreferences alloc] init];
        webConfig.preferences.javaScriptEnabled = YES;
        webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(10, 70, SCREEN_WIDTH - 20, SCREEN_HEIGHT - 150)
                                                configuration:webConfig];
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
#pragma mark - local html file loading method
        [webView loadHTMLString:html baseURL:URLBase];
#pragma mark - network request loading mode
//        NSURLRequest * request = [NSURLRequest request WithURL:[NSURL url WithString:@"]// url address of privacy protocol
//                                                 cachePolicy:NSURLRequestReloadIgnoringCacheData
//                                             timeoutInterval:3.0];
//        [webView loadRequest:request];
        
        [_backgroundView addSubview:webView];
        
        _webView = webView;
    }
    return _webView;
}

- (UIButton *)btnAgree {
    if (!_btnAgree) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(CGRectGetMidX(_webView.frame) - 50, CGRectGetMaxY(_webView.frame) + 10, 100, 44);
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitle:@"Agree" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        
        _btnAgree = btn;
    }
    return _btnAgree;
}

- (void)btnClick {
    NSMutableDictionary *configInfo = [NSMutableDictionary dictionaryWithContentsOfFile:[kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", LocalPath_ProjectConfig, LocalName_ProjectConfig]]];
    [configInfo setValue:PrivacyAgreementState forKey:@"PrivacyAgreementState"];
    InsertObjectToLocalPlistFile(configInfo, LocalName_ProjectConfig, LocalPath_ProjectConfig);
    [_backgroundView removeFromSuperview];
}



@end

Note: For example, the local loading method used in the above method and the network request method, see the comment section in the specific code.

 

3. Method Call

Refer to the header file where you need it and call the interface method, usually in appdelegate.

[PrivacyAgreement shareInstance];

 

IV. Approaches to Relevant Encapsulation in Method Classes

4.1. Click on the event to write the file to the local method

/**
 Insert objects into local plist files

 @param dataSource  data source
 @param fileName    File name
 @param filePath    File path
 */
void InsertObjectToLocalPlistFile(NSMutableDictionary *dataSource, NSString *fileName, NSString *filePath) {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docPath = [kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", filePath, fileName]];
    if ([fileManager fileExistsAtPath:docPath]) {// File exists
        NSLog(@"local plist file --- existence");
        [dataSource writeToFile:[[kDocumentPath stringByAppendingPathComponent:filePath] stringByAppendingPathComponent:fileName] atomically:YES];
    }
    else {// file does not exist
        NSLog(@"local plist file --- Non-existent");
        CreateLocalPlistFile(dataSource, fileName, filePath);
    }
}

 

 

This is the content of this sharing. I hope it will be helpful to you all. Thank you!

 

Posted by norpel on Fri, 01 Feb 2019 22:36:16 -0800