forked from Countly/countly-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountlyDB.m
executable file
·268 lines (213 loc) · 9.22 KB
/
CountlyDB.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
// CountlyDB.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyDB.h"
#ifndef COUNTLY_DEBUG
#define COUNTLY_DEBUG 0
#endif
#if COUNTLY_DEBUG
# define COUNTLY_LOG(fmt, ...) NSLog(fmt, ##__VA_ARGS__)
#else
# define COUNTLY_LOG(...)
#endif
//# define COUNTLY_APP_GROUP_ID @"group.example.myapp"
#if COUNTLY_TARGET_WATCHKIT
# ifndef COUNTLY_APP_GROUP_ID
# error "Application Group Identifier not specified! Please uncomment the line above and specify it."
# endif
#import <WatchKit/WatchKit.h>
#endif
/*
Countly iOS SDK WatchKit Support
================================
To use Countly iOS SDK in WatchKit apps:
1) While adding Countly iOS SDK files to the project, make sure you select WatchKit Extension target too.
(Or add them manually to WatchKit Extension target's Build Settings > Compile Sources section)
2) Add "-DCOUNTLY_TARGET_WATCHKIT=1" flag to "Other C Flags" under WatchKit Extension target's Build Settings
3) For both WatchKit Extension target and Container App target enable App Groups under Capabilities section.
( For details: http://is.gd/ConfiguringAppGroups )
4) Uncomment COUNTLY_APP_GROUP_ID line and specify Application Group Identifier there
5) Inside awakeWithContext:(id)context method of your watch app's main entry point (InterfaceController.m by default), start Countly as usual
[[Countly sharedInstance] start:@"YOUR_APP_KEY" withHost:@"https://YOUR_API_HOST.com"];
6) That's it. You should see a new session on your Dashboard, when you run WatchKit Extension target.
And you can record custom events as usual.
*/
@interface CountlyDB()
@end
@implementation CountlyDB
+(instancetype)sharedInstance
{
static CountlyDB* s_sharedCountlyDB;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{s_sharedCountlyDB = self.new;});
return s_sharedCountlyDB;
}
-(void)createEvent:(NSString*) eventKey count:(double)count sum:(double)sum segmentation:(NSDictionary*)segmentation timestamp:(NSTimeInterval)timestamp
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:context];
[newManagedObject setValue:eventKey forKey:@"key"];
[newManagedObject setValue:@(count) forKey:@"count"];
[newManagedObject setValue:@(sum) forKey:@"sum"];
[newManagedObject setValue:@(timestamp) forKey:@"timestamp"];
[newManagedObject setValue:segmentation forKey:@"segmentation"];
[self saveContext];
}
-(void)deleteEvent:(NSManagedObject*)eventObj
{
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:eventObj];
[self saveContext];
}
-(void)addToQueue:(NSString*)postData
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Data" inManagedObjectContext:context];
#ifdef COUNTLY_TARGET_WATCHKIT
NSString* watchSegmentationKey = @"[CLY]_apple_watch";
NSString* watchModel = (WKInterfaceDevice.currentDevice.screenBounds.size.width == 136.0)?@"38mm":@"42mm";
NSString* segmentation = [NSString stringWithFormat:@"{\"%@\":\"%@\"}", watchSegmentationKey, watchModel];
NSString* escapedSegmentation = (NSString*)CFBridgingRelease(
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)segmentation,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
postData = [postData stringByAppendingFormat:@"&segment=%@", escapedSegmentation];
#endif
[newManagedObject setValue:postData forKey:@"post"];
[self saveContext];
}
-(void)removeFromQueue:(NSManagedObject*)postDataObj
{
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:postDataObj];
[self saveContext];
}
-(NSArray*) getEvents
{
NSFetchRequest *fetchRequest = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError* error = nil;
NSArray* result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (error)
{
COUNTLY_LOG(@"CoreData error %@, %@", error, [error userInfo]);
}
return result;
}
-(NSArray*) getQueue
{
NSFetchRequest *fetchRequest = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError* error = nil;
NSArray* result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (error)
{
COUNTLY_LOG(@"CoreData error %@, %@", error, [error userInfo]);
}
return result;
}
-(NSUInteger)getEventCount
{
NSFetchRequest *fetchRequest = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError* error = nil;
NSUInteger count = [[self managedObjectContext] countForFetchRequest:fetchRequest error:&error];
if (error)
{
COUNTLY_LOG(@"CoreData error %@, %@", error, [error userInfo]);
}
return count;
}
-(NSUInteger)getQueueCount
{
NSFetchRequest *fetchRequest = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Data" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSError* error = nil;
NSUInteger count = [[self managedObjectContext] countForFetchRequest:fetchRequest error:&error];
if (error)
{
COUNTLY_LOG(@"CoreData error %@, %@", error, [error userInfo]);
}
return count;
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
COUNTLY_LOG(@"CoreData error %@, %@", error, [error userInfo]);
}
}
}
- (NSURL *)applicationSupportDirectory
{
NSFileManager *fm = NSFileManager.defaultManager;
NSURL *url = [[fm URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
NSError *error = nil;
if (![fm fileExistsAtPath:[url absoluteString]])
{
[fm createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:&error];
if(error) COUNTLY_LOG(@"Can not create Application Support directory: %@", error);
}
return url;
}
#pragma mark - Core Data Instance
- (NSManagedObjectContext *)managedObjectContext
{
static NSManagedObjectContext* s_managedObjectContext;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
s_managedObjectContext = [[NSManagedObjectContext alloc] init];
[s_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
});
return s_managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
static NSManagedObjectModel* s_managedObjectModel;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *modelURL = [[NSBundle bundleForClass:[CountlyDB class]] URLForResource:@"Countly" withExtension:@"momd"];
if (modelURL == nil)
modelURL = [[NSBundle bundleForClass:[CountlyDB class]] URLForResource:@"Countly" withExtension:@"mom"];
s_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
});
return s_managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
static NSPersistentStoreCoordinator* s_persistentStoreCoordinator;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
s_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSError *error=nil;
#ifdef COUNTLY_APP_GROUP_ID
NSURL *storeURL = [[NSFileManager.defaultManager containerURLForSecurityApplicationGroupIdentifier:COUNTLY_APP_GROUP_ID] URLByAppendingPathComponent:@"Countly.sqlite"];
#else
NSURL *storeURL = [[self applicationSupportDirectory] URLByAppendingPathComponent:@"Countly.sqlite"];
#endif
[s_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
if(error)
COUNTLY_LOG(@"Store opening error %@", error);
[storeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&error];
if(error)
COUNTLY_LOG(@"Unable to exclude Countly persistent store from backups (%@), error: %@", storeURL.absoluteString, error);
});
return s_persistentStoreCoordinator;
}
@end