1. 程式人生 > >配置隱私協議

配置隱私協議

根據蘋果隱私協議新規的推出,要求所有應用包含隱私保護協議,故為此在 App 中添加了如下隱私協議模組.

首次安裝 App 的情況下預設呼叫隱私協議模組展示相關資訊一次,當用戶點選同意按鈕後,從此不再執行該模組方法.

具體 code 如下:

一.宣告(.h)

/*
 隱私協議
 */
#import <Foundation/Foundation.h>

@interface PrivacyAgreement : NSObject

+ (instancetype)shareInstance;

@end

二.實現(.m)

#import "PrivacyAgreement.h"

/** 獲取沙盒 Document 路徑*/
#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_ProjectConfig        @"ProjectConfigInfo.plist" // 本地儲存路徑設定_檔名稱
#define LocalPath_ProjectConfig        @"Project/ProjectConfigInfo/" // 本地儲存路徑設定_檔案路徑
#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;
}



/**
 渲染隱私協議檢視
 */
- (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 設定相關
 
 其中包含載入方式(本地檔案 & 網路請求)

 @return 當前控制元件
 */
- (WKWebView *)webView {
    if (!_webView) {
        NSError *error;
        // 本地 url 地址設定
        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 - 本地 html 檔案載入方式
        [webView loadHTMLString:html baseURL:URLBase];
#pragma mark - 網路請求載入方式
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]// 隱私協議的 url 地址
//                                                 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:@"同意" 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

注:如上方法中使用的本地載入的方式,若需要使用網路請求的方式,詳見具體 code 中的註釋部分.

三.方法呼叫

在需要的地方引用該標頭檔案並呼叫介面方法即可,一般在 appdelegate 中.

[PrivacyAgreement shareInstance];

四.方法類中相關封裝的方法

4.1.點選事件中檔案寫入本地的方法

/**
 插入物件至本地 plist 檔案

 @param dataSource  資料來源
 @param fileName    檔名稱
 @param filePath    檔案路徑
 */
void InsertObjectToLocalPlistFile(NSMutableDictionary *dataSource, NSString *fileName, NSString *filePath) {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docPath = [kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", filePath, fileName]];
    if ([fileManager fileExistsAtPath:docPath]) {// 檔案存在
        NSLog(@"本地 plist 檔案 --- 存在");
        [dataSource writeToFile:[[kDocumentPath stringByAppendingPathComponent:filePath] stringByAppendingPathComponent:fileName] atomically:YES];
    }
    else {// 檔案不存在
        NSLog(@"本地 plist 檔案 --- 不存在");
        CreateLocalPlistFile(dataSource, fileName, filePath);
    }
}

以上便是此次分享的內容,還望能對大家有所幫助,謝謝!