Authored by 朱小军

Merge branch '627master' into 'master'

627master



See merge request !23
... ... @@ -39,6 +39,7 @@ Pod::Spec.new do |s|
"${PODS_ROOT}/../YH_Mall/Dependences/PowerfulBannerView",
].join(' ')
}
ss.dependency "YH_FoundationKit"
end
s.subspec "AOP" do |ss|
... ... @@ -57,6 +58,7 @@ Pod::Spec.new do |s|
ss.dependency "YHEventReport/Core"
ss.dependency "YHEventReport/AOP"
ss.dependency "YHEventReport/EventCollector"
ss.dependency "YH_FoundationKit"
ss.source_files = 'YHEventReport/YHEventReport/YHEventReport/YH_EventCache/*.{h,m}'
end
... ...
... ... @@ -300,8 +300,8 @@
2EEBB0A220A978460069D069 /* YH_DeviceInfo */ = {
isa = PBXGroup;
children = (
2EEBB0A320A978C60069D069 /* YH_DeviceInfoMonitor.h */,
2EEBB0A420A978C60069D069 /* YH_DeviceInfoMonitor.m */,
2EEBB0A320A978C60069D069 /* YH_DeviceInfoMonitor.h */,
);
path = YH_DeviceInfo;
sourceTree = "<group>";
... ...
... ... @@ -121,10 +121,6 @@
+ (NSDictionary *)factoryEventAppInfo:(YH_PerformanceAppInfo*)appInfo
{
if (IsNilOrNull(appInfo)) {
return nil;
}
NSDictionary *commonInfo = [NSDictionary dictionaryWithObjectsAndKeys:
IsStrEmpty(appInfo.ps)?@"":appInfo.ps,YOHOAppReportKeyPS,
IsStrEmpty(appInfo.av)?@"":appInfo.av,YOHOAppReportKeyAV,
... ...
... ... @@ -8,9 +8,9 @@
#import <Foundation/Foundation.h>
@class YH_Reachability;
@interface YH_PerformanceAppInfo : NSObject
@property (copy, nonatomic) NSString *ak; // App key 应用标识
@property (copy, nonatomic) NSString *udid; // 设备标识
@property (copy, nonatomic) NSString *ch; // 推广渠道号
@property (copy, nonatomic) NSString *os; // 操作系统
... ... @@ -28,6 +28,8 @@
@property (copy, nonatomic) NSString *mcc; //移动设备国家代码(Mobile Country Code,MCC)
@property (copy, nonatomic) NSString *mnc; //运营商码 移动设备网络代码英语:Mobile Network Code,MNC
-(void)resetSessionID;
- (void)resetSessionID;
- (void)update;
- (void)updateNetStatusWithReachability:(YH_Reachability *)reachability;
@end
... ...
... ... @@ -18,118 +18,72 @@
#import "YH_EventUtil.h"
#import "YHEventReport.h"
#import "NSString+ER_URL.h"
#import <UserNotifications/UserNotifications.h>
#import "YH_Reachability.h"
@implementation YH_PerformanceAppInfo
- (id)init
{
- (id)init {
self = [super init];
if (self) {
self.ps = @"0";
self.idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
[self loadCarrierInfo];
_ps = @"0";
_net = @"0";
[self update];
}
return self;
}
-(void)resetSessionID{
if (self.sid) {
self.sid = nil;
}
}
- (NSString *)ca {
if (!_ca || [_ca isEqualToString:kCarrierCodeChinaUnknown]) {
[self loadCarrierInfo];
}
return _ca;
}
- (NSString*)ch
{
_ch = [[YHEventReport sharedInstance] channelId];
return _ch;
- (void)update {
self.idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] ?: @"";
self.ch = [[YHEventReport sharedInstance] channelId];
self.udid = [OpenUDID value];
self.os = @"iOS";
self.osv = [[UIDevice currentDevice] systemVersion] ?: @"Unknown";
self.av =[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: @"";
self.ab = [[NSBundle mainBundle] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey] ?: @"";
[self loadCarrierInfo];
[self loadPushStatus];
[self loadDm];
}
-(NSString *)udid{
if (!_udid) {
_udid = [OpenUDID value];
}
return _udid;
}
-(NSString *)os{
if (!_os) {
_os = @"iOS";
- (void)loadPushStatus {
if (IOS10) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:
case UNAuthorizationStatusDenied:
self.ps = @"0";
break;
default:
self.ps = @"1";
break;
}
}];
} else {
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
self.ps = @"1";
}else {
self.ps = @"0";
}
}
return _os;
}
-(NSString *)osv{
if (!_osv) {
_osv= [[UIDevice currentDevice] systemVersion];
if (!_osv) {
_osv = @"Unknown";
}
}
return _osv;
-(void)resetSessionID{
_sid = nil;
}
-(NSString *)dm{
-(void)loadDm{
if (!_dm) {
_dm = [JTSHardwareInfo hardwareIdentifier];
NSRange range = [_dm rangeOfString:@","];
if (range.location != NSNotFound) {
_dm = [_dm stringByReplacingCharactersInRange:range withString:@"_"];
}
if (!_dm) {
_dm = @"";
}
}
return _dm;
}
-(NSString *)av{
if (!_av) {
_av =[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if (!_av) {
_av = @"";
}
}
return _av;
}
-(NSString *)ab{
if (!_ab) {
_ab = [[NSBundle mainBundle] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey];
if (!_ab) {
_ab = @"";
}
}
return _ab;
}
-(NSString *)net{
if (!_net) {
YH_Reachability *wifi = [YH_Reachability reachabilityForLocalWiFi];
YH_Reachability *conn = [YH_Reachability reachabilityForInternetConnection];
if ([conn currentReachabilityStatus] == YHNetworkStatusNotReachable)
{
_net =@"0";
}
else
{
if ([wifi currentReachabilityStatus] == YHNetworkStatusReachableViaWiFi) {
_net = @"1";
}else{
_net = @"4";
}
}
}
return _net;
}
- (void)loadCarrierInfo
... ... @@ -168,6 +122,16 @@
_ca = [currentCa copy];
}
- (void)updateNetStatusWithReachability:(YH_Reachability *)reachability {
if (reachability.currentReachabilityStatus == YHNetworkStatusNotReachable) {
self.net = @"0";
} else if (reachability.currentReachabilityStatus == YHNetworkStatusReachableViaWiFi) {
self.net = @"1";
} else {
self.net = @"4";
}
}
-(NSString *)uid{
_uid = [[YHEventReport sharedInstance] uid];
return [_uid yh_md5String];
... ...
... ... @@ -48,11 +48,6 @@
- (void)reportWithPointType:(YHPointType)type pointName:(YHEventReportPointName)name parameters:(NSDictionary *)param;
/**
* 上报http请求,请在 setTaskDidCompleteBlock 中调用
*/
- (void)reportWithHttpRequestFinish:(NSURLRequest*)request response:(NSURLResponse*)response error:(NSError*)error;
/**
* @property
*
* @abstract
... ...
... ... @@ -54,12 +54,6 @@ static NSArray *kYHEventReportIgnoredViewControllerArray;
@implementation YHEventReport
/**
* @abstract
* 返回初始化好的单例
*
* @return 返回的单例
*/
+ (YHEventReport *)sharedInstance{
static YHEventReport *sharedInstance = nil;
... ... @@ -231,25 +225,6 @@ static NSArray *kYHEventReportIgnoredViewControllerArray;
}
}
- (void)reportWithHttpRequestFinish:(NSURLRequest*)request response:(NSURLResponse*)response error:(NSError*)error
{
@try {
NSString *hostInHTTPField = [request.allHTTPHeaderFields objectForKey:@"Host"];
if ([YHEventReport sharedInstance].isPerformanceTrackEnabled && [YHEventReport sharedInstance].isHttpPerformanceTrackEnable && !error && ([[request.URL host] isEqualToString:YHEventReportHttpHost] || [hostInHTTPField isEqualToString:YHEventReportHttpHost])) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];
NSString *contentLength = [NSString stringWithFormat:@"%lld",[[httpResponseHeaderFields objectForKey:@"Content-Length"] longLongValue]];
NSString *statusCode = [NSString stringWithFormat:@"%ld",(long)httpResponse.statusCode];
NSString *HTTPBodyStr = [[NSString alloc]initWithData:request.HTTPBody encoding:NSUTF8StringEncoding];
[[YH_EventCollector sharedInstance] timeEventEndWithRequestUrl:[request.URL absoluteString] HTTPMethod:request.HTTPMethod statusCode:statusCode contentLength:contentLength HTTPBodyStr:HTTPBodyStr];
}
} @catch (NSException *exception) {
YHLog(@"%@ error: %@", self, exception);
}
}
#pragma mark - Exception handle methods
// 发送本地存储的Exception数据
- (void)uploadLocalErrorData
... ...
... ... @@ -12,12 +12,4 @@
+ (YH_CrashReporter *)sharedInstance;
- (NSString *)callstackString;
- (void)handleSignal:(NSDictionary *)userInfo;
- (void)handleNSException:(NSDictionary *)userInfo;
-(NSString *)getStringFromArray:(NSArray *)array;
@end
... ...
... ... @@ -17,6 +17,15 @@
#pragma mark - C Fuctions
@interface YH_CrashReporter()
- (NSString *)callstackString;
- (void)handleSignal:(NSDictionary *)userInfo;
- (void)handleNSException:(NSDictionary *)userInfo;
-(NSString *)getStringFromArray:(NSArray *)array;
@end
void yh_sighandler(int signal)
{
const char* names[NSIG];
... ...
... ... @@ -11,7 +11,7 @@
@interface YH_EventCacheManager : NSObject
@property (nonatomic, assign) NSUInteger cacheFileUpperLimit;
@property (nonatomic, assign) NSUInteger cacheFileUpperLimit;
+ (YH_EventCacheManager *)sharedInstance;
... ... @@ -47,6 +47,6 @@
*/
- (void)pushCrashData:(NSDictionary*)data;
- (void) startUploadMode:(YHEventReportStrategy)mode timeInterval:(long)timeIntervals;
- (void)startUploadMode:(YHEventReportStrategy)mode timeInterval:(NSUInteger)timeIntervals;
@end
... ...
... ... @@ -7,7 +7,6 @@
//
#import "YH_EventCacheManager.h"
#import "YH_EventCacheFile.h"
#import <UIKit/UIKit.h>
#import "YH_EventDataSession.h"
#import "YH_EventDataFactory.h"
... ... @@ -17,25 +16,27 @@
#import "YH_AnalyticEventData.h"
#import "YHLog.h"
#import "YH_EventDataFactory.h"
#import <YH_FoundationKit/YH_FoundationKit.h>
static NSString *const kParamKeyDevice = @"device";
static NSString *const kParamKeyList = @"events";
static NSString *const kParamKeyType = @"type";
@interface YH_EventCacheManager()
//@property (strong, nonatomic) NSMutableArray *eventCacheArray;
@property (strong, nonatomic) NSMutableArray *performanceCacheArray;
@property (strong, nonatomic) NSMutableArray *infoCacheArray;//cache custom & performance,click info send in realtime
@property (strong, nonatomic) YH_EventDataSession *eventDataSession;
@property (nonatomic, assign) YHEventReportStrategy mode;
@property (nonatomic,strong)YH_PerformanceAppInfo *performanceAppInfo;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,assign)long timeInterval;
@property (nonatomic, assign) YHEventReportStrategy mode;
@property (nonatomic,strong) YH_PerformanceAppInfo *appInfo;
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong) dispatch_queue_t queue;
@property (nonatomic,assign) NSUInteger timeInterval;
@property (nonatomic, strong) YH_Reachability *intnetReachability;
@end
@implementation YH_EventCacheManager
static NSString *kParamKeyDevice = @"device";
static NSString *kParamKeyList = @"events";
static NSString *kParamKeyType = @"type";
+ (YH_EventCacheManager *)sharedInstance
{
static YH_EventCacheManager *sharedInstance = nil;
... ... @@ -50,67 +51,33 @@ static NSString *kParamKeyType = @"type";
{
self = [super init];
if (self) {
self.timeInterval = 30;
self.mode = YHEventReportStrategyInterval;
self.performanceAppInfo = [[YH_PerformanceAppInfo alloc] init];
self.timer = [NSTimer timerWithTimeInterval:self.timeInterval target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode: NSRunLoopCommonModes];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleApplicationBackgrounding)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleDidFinishLaunch)
name:UIApplicationDidFinishLaunchingNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleTerminate)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshPushStatus) name:UIApplicationWillEnterForegroundNotification object:nil];
[self refreshPushStatus];
[[YH_Reachability reachabilityForInternetConnection] startNotifier];
_timeInterval = 30;
_mode = YHEventReportStrategyInterval;
_appInfo = [[YH_PerformanceAppInfo alloc] init];
_eventDataSession = [[YH_EventDataSession alloc] init];
_infoCacheArray = [NSMutableArray array];
_queue = yh_gcdSerialQueue(@"cn.yoho.buy.eventReport.serial");
_intnetReachability = [YH_Reachability reachabilityForInternetConnection];
[_intnetReachability startNotifier];
[self startTimer];
[self yh_observeNotificationName:UIApplicationDidReceiveMemoryWarningNotification action:@selector(handleMemoryWarning)];
[self yh_observeNotificationName:UIApplicationDidEnterBackgroundNotification action:@selector(handleApplicationBackgrounding)];
[self yh_observeNotificationName:UIApplicationWillEnterForegroundNotification action:@selector(handleApplicationForerounding)];
[self yh_observeNotificationName:UIApplicationDidFinishLaunchingNotification action:@selector(handleDidFinishLaunch)];
[self yh_observeNotificationName:UIApplicationWillTerminateNotification action:@selector(handleTerminate)];
[self yh_observeNotificationName:UIApplicationWillEnterForegroundNotification action:@selector(refreshAppInfo)];
[self yh_observeNotificationName:kYHReachabilityChangedNotification action:@selector(networkStateChange:)];
}
return self;
}
- (void)dealloc
{
[self.timer invalidate];
[[YH_Reachability reachabilityForInternetConnection] stopNotifier];
[self cancelTimer];
[_intnetReachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Getters
- (NSMutableArray*)performanceCacheArray
{
if (_performanceCacheArray == nil) {
_performanceCacheArray = [[NSMutableArray alloc]initWithCapacity:0];
}
return _performanceCacheArray;
}
- (YH_EventDataSession*)eventDataSession
{
if (_eventDataSession == nil) {
_eventDataSession = [[YH_EventDataSession alloc]init];
}
return _eventDataSession;
}
#pragma mark - public
- (void)pushUIControlEvent:(NSString *)viewPath title:(NSString *)title content:(NSString *)content yh_pageName:(NSString *)yh_pageName yh_typeId:(NSString *)yh_typeId alias: (NSString *)yh_Alias
... ... @@ -119,7 +86,6 @@ static NSString *kParamKeyType = @"type";
YHLog(@"UIControlEvent: viewPath can't empty!!!");
return;
}
NSDictionary *param = @{
kYHEventReportClickViewPath: viewPath,
kYHEventReportClickTitle: title ?: @"",
... ... @@ -128,16 +94,15 @@ static NSString *kParamKeyType = @"type";
kYHEventReportClickVCPageName: yh_pageName?:@"",
kYHEventReportClickVCAlias: yh_Alias?:@"",
};
YHLog(@"UIControlEvent: %@", param);
[self pushEventData:param];
}
- (void)pushEventData:(NSDictionary*)data
{
[self pushData:[[YH_AnalyticEventData sharedInstance] analyticEventParameters:data] dataType:YHEventReportDataTypeClickEvent];
dispatch_async(self.queue, ^{
[self pushData:[[YH_AnalyticEventData sharedInstance] analyticEventParameters:data] dataType:YHEventReportDataTypeClickEvent];
});
}
- (void)pushPerformanceData:(NSDictionary*)data pointName:(YHEventReportPointName)name
... ... @@ -146,19 +111,18 @@ static NSString *kParamKeyType = @"type";
[performanceDic setObject:@"PERFORMANCE" forKey:YOHOAppReportKeyPT];
[performanceDic setObject:[YH_EventDataFactory getPointName:name] forKey:YOHOAppReportKeyPN];
NSMutableDictionary *eventDic = [[YH_EventDataFactory factoryEventAppInfo:self.performanceAppInfo]mutableCopy];
NSMutableDictionary *eventDic = [NSMutableDictionary dictionary];
if (!IsDictionaryClass(eventDic)) {
return;
}
if (IsDictionaryClass(performanceDic)) {
[eventDic addEntriesFromDictionary:performanceDic];
}
if (IsDictionaryClass(eventDic)) {
if (IsDictionaryClass(data)) {
[eventDic setObject:data forKey:YOHOAppReportKeyPARAM];
}
[self pushData:eventDic dataType:YHEventReportDataTypePerformance];
dispatch_async(self.queue, ^{
[eventDic addEntriesFromDictionary:[YH_EventDataFactory factoryEventAppInfo:self.appInfo]];
[self pushData:eventDic dataType:YHEventReportDataTypePerformance];
});
}
- (void)pushCustomData:(NSDictionary*)data pointType:(YHPointType)type pointName:(YHEventReportPointName)name{
... ... @@ -166,103 +130,96 @@ static NSString *kParamKeyType = @"type";
[performanceDic setObject:[YH_EventDataFactory getPointType:type] forKey:YOHOAppReportKeyPT];
[performanceDic setObject:[YH_EventDataFactory getPointName:name] forKey:YOHOAppReportKeyPN];
NSMutableDictionary *eventDic = [[YH_EventDataFactory factoryEventAppInfo:self.performanceAppInfo]mutableCopy];
if (!IsDictionaryClass(eventDic)) {
return;
}
if (IsDictionaryClass(performanceDic)) {
dispatch_async(self.queue, ^{
NSMutableDictionary *eventDic = [[YH_EventDataFactory factoryEventAppInfo:self.appInfo] mutableCopy];
[eventDic addEntriesFromDictionary:performanceDic];
}
switch (type) {
case YHPT_NETWORK:
switch (type) {
case YHPT_NETWORK:
{
[self.eventDataSession getbaiduNetStatus:eventDic completionBlock:^(NSTimeInterval cts, NSInteger errCode) {
NSMutableDictionary *appendDict = [[NSMutableDictionary alloc] initWithDictionary:data];
[appendDict setValue:[NSString stringWithFormat:@"%zd",errCode] forKey:YOHOAppReportKeyJsonKeyErrorTEC];
[appendDict setValue:[NSString stringWithFormat:@"%ld",(long)cts] forKey:YOHOAppReportKeyJsonKeyErrorCTS];
[eventDic setValue:appendDict forKey:YOHOAppReportKeyPARAM];
[self pushData:eventDic dataType:YHEventReportDataTypeCustom];
}];
[self checkBaiduStatusWithEventData:eventDic customData:data];
}
break;
case YHPT_AD:
break;
case YHPT_AD:
{
if ([data valueForKey:YOHOAppReportKeyJsonKeyErrorTEC]) {
[self.eventDataSession getbaiduNetStatus:eventDic completionBlock:^(NSTimeInterval cts, NSInteger errCode) {
NSMutableDictionary *appendDict = [[NSMutableDictionary alloc] initWithDictionary:data];
[appendDict setValue:[NSString stringWithFormat:@"%zd",errCode] forKey:YOHOAppReportKeyJsonKeyErrorTEC];
[appendDict setValue:[NSString stringWithFormat:@"%ld",(long)cts] forKey:YOHOAppReportKeyJsonKeyErrorCTS];
[eventDic setValue:appendDict forKey:YOHOAppReportKeyPARAM];
[self pushData:eventDic dataType:YHEventReportDataTypeCustom];
}];
[self checkBaiduStatusWithEventData:eventDic customData:data];
} else {
[eventDic setValue:data forKey:YOHOAppReportKeyPARAM];
[self pushData:eventDic dataType:YHEventReportDataTypeCustom];
}
}
break;
default:
break;
default:
{
[eventDic setValue:data forKey:YOHOAppReportKeyPARAM];
[self pushData:eventDic dataType:YHEventReportDataTypeCustom];
}
break;
}
break;
}
});
}
- (void)pushCrashData:(NSDictionary*)data{
NSMutableDictionary *eventDic = [[YH_EventDataFactory factoryEventAppInfo:self.performanceAppInfo]mutableCopy];
if (!IsDictionaryClass(eventDic) ||!IsDictionaryClass(data)) {
- (void)checkBaiduStatusWithEventData:(NSMutableDictionary *)eventDic customData:(NSDictionary *)data {
weakify(self);
[self.eventDataSession getbaiduNetStatusWithCompletionBlock:^(NSTimeInterval cts, NSInteger errCode) {
strongify(self);
NSMutableDictionary *appendDict = [[NSMutableDictionary alloc] initWithDictionary:data];
[appendDict setValue:[NSString stringWithFormat:@"%zd",errCode] forKey:YOHOAppReportKeyJsonKeyErrorTEC];
[appendDict setValue:[NSString stringWithFormat:@"%ld",(long)cts] forKey:YOHOAppReportKeyJsonKeyErrorCTS];
[eventDic setValue:appendDict forKey:YOHOAppReportKeyPARAM];
dispatch_async(self.queue, ^{
[self pushData:eventDic dataType:YHEventReportDataTypeCustom];
});
}];
}
- (void)pushCrashData:(NSDictionary*)data {
if (!IsDictionaryClass(data) || data.count <= 0) {
return;
}
[eventDic addEntriesFromDictionary:data];
[self pushData:[eventDic copy] dataType:YHEventReportDataTypeCustom];
dispatch_async(self.queue, ^{
NSMutableDictionary *eventDic = [[YH_EventDataFactory factoryEventAppInfo:self.appInfo] mutableCopy];
[eventDic addEntriesFromDictionary:data];
[self pushData:[eventDic copy] dataType:YHEventReportDataTypeCustom];
});
}
#pragma mark - private
- (void)pushData:(NSDictionary*)data dataType:(YHEventReportDataType)type
{
if (type == YHEventReportDataTypeClickEvent) {
[self.eventDataSession uploadEventData:data tag:nil result:^(BOOL isSuc, id tag, NSError *error) {
}];
[self.eventDataSession uploadEventData:data tag:nil result:nil];
}else {
if (self.mode == YHEventReportStrategyInterval) {
@synchronized (self.performanceCacheArray) {
[self.performanceCacheArray addObject:data];
}
[self.infoCacheArray addObject:data];
}else{
weakify(self);
[self.eventDataSession uploadPerformanceData:[self getPerformanceFormatData:@[data] type:YHEventReportTrackDataTypeNONE] tag:nil result:^(BOOL isSuc, id tag, NSError *error) {
if (!isSuc) {
strongify(self);
dispatch_async(self.queue, ^{
[self.infoCacheArray addObject:data];
});
}
}];
}
}
}
- (void) startUploadMode:(YHEventReportStrategy)mode timeInterval:(long)timeIntervals;
- (void)startUploadMode:(YHEventReportStrategy)mode timeInterval:(NSUInteger)timeIntervals;
{
_mode = mode;
self.timeInterval = timeIntervals;
if (mode == YHEventReportStrategyInterval) {
if (self.timer == nil) {
//定时上传
self.timer = [NSTimer timerWithTimeInterval:self.timeInterval target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode: NSRunLoopCommonModes];
dispatch_async(self.queue, ^{
_mode = mode;
if (timeIntervals > 0 && timeIntervals < 5 * 60) {
self.timeInterval = timeIntervals;
}
}else{
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
if (mode == YHEventReportStrategyInterval) {
[self startTimer];
}else{
[self cancelTimer];
}
}
});
}
- (NSMutableDictionary*)getPerformanceFormatData:(NSArray*)dataArray type:(YHEventReportTrackDataType)type
... ... @@ -278,135 +235,151 @@ static NSString *kParamKeyType = @"type";
}
[performanceAryDic setObject:[YH_EventDataFactory getDataType:type] forKey:kParamKeyType];
[performanceAryDic setObject:[YH_EventDataFactory getDeviceInfo:self.performanceAppInfo] forKey:kParamKeyDevice];
[performanceAryDic setObject:[YH_EventDataFactory getDeviceInfo:self.appInfo] forKey:kParamKeyDevice];
return performanceAryDic;
}
-(NSString *)getPointName:(YHEventReportPointName)pointName{
NSString *str = @"";
switch (pointName) {
case YHPN_VIEWCONTROLLER:
str = @"PAGE";
break;
case YHPN_WEBVIEW:
str = @"WEBVIEW";
break;
case YHPN_IMAGEVIEW:
str = @"IMAGE";
break;
case YHPN_BUTTON:
str = @"BUTTON";
break;
case YHPN_GESTURERECOGNIZER:
str = @"GESTURERECOGNIZER";
break;
default:
break;
}
return str;
}
-(NSString *)getDataType:(YHEventReportTrackDataType)type{
NSString *str = @"";
switch (type) {
case YHEventReportTrackDataTypeStart:
str = @"start";
break;
case YHEventReportTrackDataTypeDestory:
str = @"destory";
break;
case YHEventReportTrackDataTypeStop:
str = @"stop";
break;
case YHEventReportTrackDataTypeHeartbeat:
str = @"hb";
break;
case YHEventReportTrackDataTypeNONE:
str = @"realTime";
break;
default:
break;
}
return str;
}
- (void)refreshPushStatus
{
if (IOS10) {// system is iOS10
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:
self.performanceAppInfo.ps = @"0";
break;
case UNAuthorizationStatusDenied:
self.performanceAppInfo.ps = @"0";
break;
default:
self.performanceAppInfo.ps = @"1";
break;
}
}];
} else {//iOS8
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
self.performanceAppInfo.ps = @"1";
}else {
self.performanceAppInfo.ps = @"0";
}
}
- (void)refreshAppInfo {
dispatch_async(self.queue, ^{
[self.appInfo update];
});
}
#pragma mark - NSNotification
- (void)handleMemoryWarning
{
if (self.mode == YHEventReportStrategyInterval) {
@synchronized (self.performanceCacheArray) {
[self.performanceCacheArray removeAllObjects];
dispatch_async(self.queue, ^{
if (self.mode == YHEventReportStrategyInterval) {
//todo save to disk
[self.infoCacheArray removeAllObjects];
}
}
});
}
- (void)handleDidFinishLaunch
{
if (self.mode == YHEventReportStrategyInterval) {
[self uploadPerformanceDataWithType:YHEventReportTrackDataTypeStart];
}
dispatch_async(self.queue, ^{
if (self.mode == YHEventReportStrategyInterval) {
[self loadDiskCachedEventInfoToMemArray:self.infoCacheArray];
[self clearDiskCache];
[self uploadEventAndCustomInfo:self.infoCacheArray type:YHEventReportTrackDataTypeStart completion:^(BOOL isSuccess) {
if (isSuccess) {
dispatch_async(self.queue, ^{
[self.infoCacheArray removeAllObjects];
});
}
}];
}
});
}
- (void)handleTerminate
{
if (self.mode == YHEventReportStrategyInterval) {
[self uploadPerformanceDataWithType:YHEventReportTrackDataTypeDestory];
}
dispatch_sync(self.queue, ^{// block until send over
if (self.mode == YHEventReportStrategyInterval) {
NSArray *array = [self.infoCacheArray copy];
[self.infoCacheArray removeAllObjects];
[self saveToDiskOfInfo:array];
[self uploadEventAndCustomInfo:array type:YHEventReportTrackDataTypeDestory completion:^(BOOL isSuccess) {
if (isSuccess) {
[self clearDiskCache];
}
}];
}
});
}
- (void)handleApplicationBackgrounding
{
[self.performanceAppInfo resetSessionID];
if (self.mode == YHEventReportStrategyInterval) {
[self uploadPerformanceDataWithType:YHEventReportTrackDataTypeStop];
}
dispatch_async(self.queue, ^{
[self.appInfo resetSessionID];
if (self.mode == YHEventReportStrategyInterval) {
NSArray *array = [self.infoCacheArray copy];
[self.infoCacheArray removeAllObjects];
[self saveToDiskOfInfo:array];
[self uploadEventAndCustomInfo:array type:YHEventReportTrackDataTypeStop completion:^(BOOL isSuccess) {
if (isSuccess) {
[self clearDiskCache];
}
}];
}
});
}
- (void)handleApplicationForerounding {
dispatch_async(self.queue, ^{
[self loadDiskCachedEventInfoToMemArray:self.infoCacheArray];
[self clearDiskCache];
});
}
- (void)networkStateChange:(NSNotification *)note {
dispatch_async(self.queue, ^{
[self.appInfo updateNetStatusWithReachability:self.intnetReachability];
});
}
#pragma mark - timer
- (void)timerAction
{
[self uploadPerformanceDataWithType:YHEventReportTrackDataTypeHeartbeat];
- (void)startTimer {
if (!_timer) {
weakify(self);
_timer = yh_gcdTimer(_queue, _timeInterval, ^{
strongify(self);
[self timerAction];
});
}
}
- (void)cancelTimer {
if (_timer) {
dispatch_cancel(_timer);
_timer = nil;
}
}
- (void)timerAction {
if (!self.infoCacheArray.count) {
return;
}
[self uploadEventAndCustomInfo:self.infoCacheArray type:YHEventReportTrackDataTypeHeartbeat completion:^(BOOL isSuccess) {
if (isSuccess) {
dispatch_async(self.queue, ^{
[self.infoCacheArray removeAllObjects];
});
}
}];
}
#pragma mark - upload performance data
-(void)uploadPerformanceDataWithType:(YHEventReportTrackDataType)type{
@synchronized (self.performanceCacheArray) {
[self.eventDataSession uploadPerformanceData:[self getPerformanceFormatData:self.performanceCacheArray type:type] tag:nil result:^(BOOL isSuc, id tag, NSError *error) {
}];
-(void)uploadEventAndCustomInfo:(NSArray *)infoCacheArray type:(YHEventReportTrackDataType)type completion:(void(^)(BOOL isSuccess))completion {
[self.eventDataSession uploadPerformanceData:[self getPerformanceFormatData:infoCacheArray type:type] tag:nil result:^(BOOL isSuc, id tag, NSError *error) {
BLOCK_EXEC(completion, isSuc);
}];
}
- (void)saveToDiskOfInfo:(NSArray *)infoArray {
[infoArray writeToFile:[self cachePath] atomically:YES];
}
- (void)loadDiskCachedEventInfoToMemArray:(NSMutableArray *)memArray {
if (![[NSFileManager defaultManager] fileExistsAtPath:[self cachePath]]) {
return;
}
@synchronized (self.performanceCacheArray) {
[self.performanceCacheArray removeAllObjects];
NSArray *array = [NSArray arrayWithContentsOfFile:[self cachePath]];
if (array.count) {
[memArray addObjectsFromArray:array];
}
}
- (void)clearDiskCache {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self cachePath]]) {
[[NSFileManager defaultManager] removeItemAtPath:[self cachePath] error:nil];
}
}
- (NSString *)cachePath {
return [NSTemporaryDirectory() stringByAppendingPathComponent:@"event.cache"];
}
@end
... ...
... ... @@ -9,22 +9,26 @@
#import <Foundation/Foundation.h>
#import "YHEventReportMacros.h"
typedef void (^YHDataUploadCompletion)(BOOL isSuc,id tag, NSError *error);
typedef void (^YHBaiduCheckCompletion)(NSTimeInterval cts, NSInteger errCode);
@interface YH_EventDataSession : NSObject
/**
* @abstract
* 上传event数据
* 上传click event数据
* //data -array -dic
*/
- (void) uploadEventData:(id)parameters tag:(id)tag result:(void (^)(BOOL isSuc,id tag, NSError *error))result;
- (void)uploadEventData:(id)parameters tag:(id)tag result:(YHDataUploadCompletion)result;
/**
* @abstract
* 上传性能数据
* 上传性能数据 & custome
* //data -array -dic
*/
- (void) uploadPerformanceData:(id)parameters tag:(id)tag result:(void (^)(BOOL isSuc,id tag, NSError *error))result;
- (void)uploadPerformanceData:(id)parameters tag:(id)tag result:(YHDataUploadCompletion)result;
//图片or接口异常下百度连接状态上报
- (void)getbaiduNetStatus:(NSDictionary *)parameters completionBlock:(void (^)(NSTimeInterval cts, NSInteger errCode))diagnosisBlock;
- (void)getbaiduNetStatusWithCompletionBlock:(YHBaiduCheckCompletion)diagnosisBlock;
@end
... ...
... ... @@ -13,59 +13,32 @@
#import "NSData+YHERGZip.h"
#import "NSString+ER_URL.h"
#import "YHEventReport.h"
#import <YH_FoundationKit/YH_FoundationKit.h>
#define kYOHOEventReportURL @"http://analysis.yohobuy.com/yas_mobile"//@"http://172.16.10.128:8081/eventreport"
#define kYOHOPerformanceReportURL @"http://app.yoho.cn/collect/v3"//@"http://172.16.6.108/collect/v2"
#define kYOHONetworkDiagnosisURL @"https://m.baidu.com"
static NSString *const kYOHOEventReportURL = @"http://analysis.yohobuy.com/yas_mobile";//@"http://172.16.10.128:8081/eventreport"
static NSString *const kYOHOPerformanceReportURL = @"http://app.yoho.cn/collect/v3";//@"http://172.16.6.108/collect/v2"
static NSString *const kYOHONetworkDiagnosisURL = @"https://m.baidu.com";
@interface YH_EventDataSession()
//request template
@property (nonatomic,strong)NSMutableURLRequest *uploadEventRequest;
@property (nonatomic,strong)NSMutableURLRequest *uploadPerformanceRequest;
@property (nonatomic,strong)NSMutableURLRequest *networkDiagnosisRequest;
@property (nonatomic,strong)NSURLSession *uploadSession;
@property (nonatomic,assign)BOOL canUpload;
@end
@implementation YH_EventDataSession
- (instancetype)init
{
self = [super init];
if (self) {
self.canUpload = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kYHReachabilityChangedNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - public
- (void)uploadEventData:(id)parameters tag:(id)tag result:(void (^)(BOOL isSuc,id tag, NSError *error))result
- (void)uploadEventData:(id)parameters tag:(id)tag result:(YHDataUploadCompletion)result
{
#if !TARGET_IPHONE_SIMULATOR
if (![YHEventReport sharedInstance].isClickEventTrackEnabled) {
return;
}
if (!self.canUpload) {
return;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSString *parsJsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *parsStr = [[NSString stringWithFormat:@"_mlogs=%@",erSafeValue(parsJsonStr)]er_encodedString];
NSData* xmlData = [parsStr dataUsingEncoding:NSUTF8StringEncoding];
... ... @@ -75,10 +48,9 @@
[self.uploadEventRequest setValue:(@(self.uploadEventRequest.HTTPBody.length)).description forHTTPHeaderField:@"Content-Length"];
NSURLSessionDataTask *task = [self.uploadSession dataTaskWithRequest:self.uploadEventRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
//YHLog(@"error = %@",error);
result(NO,tag,error);
BLOCK_EXEC(result, NO, tag, error);
}else{
result(YES,tag,nil);
BLOCK_EXEC(result, YES, tag, nil);
}
}];
... ... @@ -86,20 +58,14 @@
#endif
}
- (void)uploadPerformanceData:(id)parameters tag:(id)tag result:(void (^)(BOOL isSuc,id tag, NSError *error))result
- (void)uploadPerformanceData:(id)parameters tag:(id)tag result:(YHDataUploadCompletion)result
{
#if !TARGET_IPHONE_SIMULATOR
if (![YHEventReport sharedInstance].isPerformanceTrackEnabled && ![YHEventReport sharedInstance].isAppReportEnable) {
return;
}
if (!self.canUpload) {
return;
}
NSData *postData = [self getBodyData:parameters];
if (!postData) {
NSError *nullError = [[NSError alloc] initWithDomain:@"YoHoErrorDomain" code:-11111 userInfo:@{NSLocalizedDescriptionKey:@"data 不能为空!"}];
result(NO,nil,nullError);
BLOCK_EXEC(result, NO, tag, nullError);
return;
}
... ... @@ -107,10 +73,9 @@
[self.uploadPerformanceRequest setValue:(@(self.uploadPerformanceRequest.HTTPBody.length)).description forHTTPHeaderField:@"Content-Length"];
NSURLSessionDataTask *task = [self.uploadSession dataTaskWithRequest:self.uploadPerformanceRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
//YHLog(@"error = %@",error);
result(NO,tag,error);
BLOCK_EXEC(result, NO, tag, error);
}else{
result(YES,tag,nil);
BLOCK_EXEC(result, YES, tag, nil);
}
}];
... ... @@ -119,7 +84,7 @@
}
#pragma mark 百度连接状态诊断
- (void)getbaiduNetStatus:(NSDictionary *)parameters completionBlock:(void (^)(NSTimeInterval cts, NSInteger errCode))diagnosisBlock
- (void)getbaiduNetStatusWithCompletionBlock:(YHBaiduCheckCompletion)diagnosisBlock
{
if (!diagnosisBlock) {
return;
... ... @@ -138,9 +103,9 @@
} else {
ect = error.code;
}
diagnosisBlock(durationTime,ect);
BLOCK_EXEC(diagnosisBlock, durationTime, ect);
}else{
diagnosisBlock(durationTime,httpResponse.statusCode);
BLOCK_EXEC(diagnosisBlock, durationTime, httpResponse.statusCode);
}
}];
... ... @@ -204,23 +169,7 @@
NSURL *url = [NSURL URLWithString:kYOHONetworkDiagnosisURL];
_networkDiagnosisRequest = [NSMutableURLRequest requestWithURL:url];
}
return _networkDiagnosisRequest;
}
#pragma mark - NSNotificationCenter
- (void)networkStateChange
{
YH_Reachability *wifi = [YH_Reachability reachabilityForLocalWiFi];
YH_Reachability *conn = [YH_Reachability reachabilityForInternetConnection];
if ([wifi currentReachabilityStatus] == YHNetworkStatusNotReachable && [conn currentReachabilityStatus] == YHNetworkStatusNotReachable) {
//YHLog(@"没有网络");
self.canUpload = NO;
}else {
//YHLog(@"有网络");
self.canUpload = YES;
}
}
@end
... ...