forked from Countly/countly-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountlyPersistency.m
314 lines (255 loc) · 8.82 KB
/
CountlyPersistency.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// CountlyPersistency.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyCommon.h"
@interface CountlyPersistency()
@property (nonatomic, strong) NSMutableArray* queuedRequests;
@property (nonatomic, strong) NSMutableArray* recordedEvents;
@property (nonatomic, strong) NSMutableDictionary* startedEvents;
@end
@implementation CountlyPersistency
NSString* const kCountlyQueuedRequestsPersistencyKey = @"kCountlyQueuedRequestsPersistencyKey";
NSString* const kCountlyStartedEventsPersistencyKey = @"kCountlyStartedEventsPersistencyKey";
NSString* const kCountlyTVOSNSUDKey = @"kCountlyTVOSNSUDKey";
NSString* const kCountlyStoredDeviceIDKey = @"kCountlyStoredDeviceIDKey";
NSString* const kCountlyWatchParentDeviceIDKey = @"kCountlyWatchParentDeviceIDKey";
NSString* const kCountlyStarRatingStatusKey = @"kCountlyStarRatingStatusKey";
+ (instancetype)sharedInstance
{
static CountlyPersistency* s_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{s_sharedInstance = self.new;});
return s_sharedInstance;
}
- (instancetype)init
{
self = [super init];
if (self)
{
#if TARGET_OS_TV
NSData* readData = [NSUserDefaults.standardUserDefaults objectForKey:kCountlyTVOSNSUDKey];
#else
NSData* readData = [NSData dataWithContentsOfURL:[self storageFileURL]];
#endif
if(readData)
{
NSDictionary* readDict = [NSKeyedUnarchiver unarchiveObjectWithData:readData];
self.queuedRequests = [readDict[kCountlyQueuedRequestsPersistencyKey] mutableCopy];
}
if(!self.queuedRequests)
self.queuedRequests = NSMutableArray.new;
if(!self.startedEvents)
self.startedEvents = NSMutableDictionary.new;
self.recordedEvents = NSMutableArray.new;
}
return self;
}
#pragma mark ---
- (void)addToQueue:(NSString *)queryString
{
@synchronized (self)
{
[self.queuedRequests addObject:queryString];
if(self.queuedRequests.count > self.storedRequestsLimit && !CountlyConnectionManager.sharedInstance.connection)
{
[self.queuedRequests removeObjectsInRange:(NSRange){0,1}];
}
}
}
- (void)removeFromQueue:(NSString *)queryString
{
@synchronized (self)
{
[self.queuedRequests removeObject:queryString];
}
}
- (NSString *)firstItemInQueue
{
@synchronized (self)
{
return self.queuedRequests.firstObject;
}
}
#pragma mark ---
- (void)recordEvent:(CountlyEvent *)event
{
@synchronized (self.recordedEvents)
{
[self.recordedEvents addObject:event];
if (self.recordedEvents.count >= self.eventSendThreshold)
[CountlyConnectionManager.sharedInstance sendEvents];
}
}
- (NSString *)serializedRecordedEvents
{
NSMutableArray* tempArray = NSMutableArray.new;
@synchronized (self.recordedEvents)
{
if(self.recordedEvents.count == 0)
return nil;
for (CountlyEvent* event in self.recordedEvents.copy)
{
[tempArray addObject:[event dictionaryRepresentation]];
[self.recordedEvents removeObject:event];
}
}
return [tempArray JSONify];
}
#pragma mark ---
- (void)recordTimedEvent:(CountlyEvent *)event
{
@synchronized (self.startedEvents)
{
if(self.startedEvents[event.key])
{
COUNTLY_LOG(@"Event with key '%@' already started!", event.key);
return;
}
self.startedEvents[event.key] = event;
}
}
- (CountlyEvent *)timedEventForKey:(NSString *)key
{
@synchronized (self.startedEvents)
{
CountlyEvent *event = self.startedEvents[key];
[self.startedEvents removeObjectForKey:key];
return event;
}
}
- (void)clearAllTimedEvents
{
@synchronized (self.startedEvents)
{
[self.startedEvents removeAllObjects];
}
}
#pragma mark ---
- (NSURL *)storageFileURL
{
NSString* const kCountlyPersistencyFileName = @"Countly.dat";
static NSURL *url = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
{
url = [[NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
#if TARGET_OS_OSX
url = [url URLByAppendingPathComponent:NSBundle.mainBundle.bundleIdentifier];
#endif
NSError *error = nil;
if (![NSFileManager.defaultManager fileExistsAtPath:url.absoluteString])
{
[NSFileManager.defaultManager createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:&error];
if(error){ COUNTLY_LOG(@"Application Support directory can not be created: \n%@", error); }
}
url = [url URLByAppendingPathComponent:kCountlyPersistencyFileName];
});
return url;
}
- (void)saveToFile
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
{
[self saveToFileSync];
});
}
- (void)saveToFileSync
{
NSDictionary* saveDict = @{
kCountlyQueuedRequestsPersistencyKey:self.queuedRequests
};
NSData* saveData;
@synchronized (self)
{
saveData = [NSKeyedArchiver archivedDataWithRootObject:saveDict];
}
#if TARGET_OS_TV
[NSUserDefaults.standardUserDefaults setObject:saveData forKey:kCountlyTVOSNSUDKey];
[NSUserDefaults.standardUserDefaults synchronize];
#else
[saveData writeToFile:[self storageFileURL].path atomically:YES];
#endif
}
#pragma mark ---
- (NSString* )retrieveStoredDeviceID
{
NSString* retrievedDeviceID = [NSUserDefaults.standardUserDefaults objectForKey:kCountlyStoredDeviceIDKey];
if(retrievedDeviceID)
{
COUNTLY_LOG(@"Device ID successfully retrieved from UserDefaults: %@", retrievedDeviceID);
return retrievedDeviceID;
}
NSDictionary *keychainDict =
@{
(__bridge id)kSecAttrAccount: kCountlyStoredDeviceIDKey,
(__bridge id)kSecAttrService: kCountlyStoredDeviceIDKey,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleAlways,
(__bridge id)kSecReturnData: (__bridge id)kCFBooleanTrue,
(__bridge id)kSecReturnAttributes: (__bridge id)kCFBooleanTrue
};
CFDictionaryRef resultDictRef = nil;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)keychainDict, (CFTypeRef *)&resultDictRef);
if (status == noErr)
{
NSDictionary *resultDict = (__bridge_transfer NSDictionary *)resultDictRef;
NSData *data = resultDict[(__bridge id)kSecValueData];
if (data)
{
retrievedDeviceID = [data stringUTF8];
COUNTLY_LOG(@"Device ID successfully retrieved from KeyChain: %@", retrievedDeviceID);
[NSUserDefaults.standardUserDefaults setObject:retrievedDeviceID forKey:kCountlyStoredDeviceIDKey];
[NSUserDefaults.standardUserDefaults synchronize];
return retrievedDeviceID;
}
}
COUNTLY_LOG(@"Device ID can not be retrieved!");
return nil;
}
- (void)storeDeviceID:(NSString *)deviceID
{
[NSUserDefaults.standardUserDefaults setObject:deviceID forKey:kCountlyStoredDeviceIDKey];
[NSUserDefaults.standardUserDefaults synchronize];
NSDictionary *keychainDict =
@{
(__bridge id)kSecAttrAccount: kCountlyStoredDeviceIDKey,
(__bridge id)kSecAttrService: kCountlyStoredDeviceIDKey,
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleAlways,
(__bridge id)kSecValueData: [deviceID dataUTF8]
};
SecItemDelete((__bridge CFDictionaryRef)keychainDict);
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)keychainDict, NULL);
if(status == noErr)
{
COUNTLY_LOG(@"Device ID successfully stored: %@", deviceID);
}
else
{
COUNTLY_LOG(@"Device ID can not be stored! %d", status);
}
}
- (NSString *)retrieveWatchParentDeviceID
{
return [NSUserDefaults.standardUserDefaults objectForKey:kCountlyWatchParentDeviceIDKey];
}
- (void)storeWatchParentDeviceID:(NSString *)deviceID
{
[NSUserDefaults.standardUserDefaults setObject:deviceID forKey:kCountlyWatchParentDeviceIDKey];
[NSUserDefaults.standardUserDefaults synchronize];
}
- (NSDictionary *)retrieveStarRatingStatus
{
NSDictionary* status = [NSUserDefaults.standardUserDefaults objectForKey:kCountlyStarRatingStatusKey];
if(!status)
status = NSDictionary.new;
return status;
}
- (void)storeStarRatingStatus:(NSDictionary *)status
{
[NSUserDefaults.standardUserDefaults setObject:status forKey:kCountlyStarRatingStatusKey];
[NSUserDefaults.standardUserDefaults synchronize];
}
@end