-
Notifications
You must be signed in to change notification settings - Fork 244
/
CountlyContentBuilderInternal.m
234 lines (189 loc) · 7.62 KB
/
CountlyContentBuilderInternal.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
// CountlyContent.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyContentBuilderInternal.h"
#import "CountlyWebViewManager.h"
//TODO: improve logging, check edge cases
NSString* const kCountlyEndpointContent = @"/o/sdk/content";
NSString* const kCountlyCBFetchContent = @"queue";
@implementation CountlyContentBuilderInternal {
BOOL _isRequestQueueLocked;
NSTimer *_requestTimer;
NSTimer *_minuteTimer;
}
#if (TARGET_OS_IOS)
+ (instancetype)sharedInstance {
static CountlyContentBuilderInternal *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (instancetype)init
{
if (self = [super init])
{
self.requestInterval = 30.0;
_requestTimer = nil;
}
return self;
}
- (void)enterContentZone {
[self enterContentZone:@[]];
}
- (void)enterContentZone:(NSArray<NSString *> *)tags {
[_minuteTimer invalidate];
_minuteTimer = nil;
if (!CountlyConsentManager.sharedInstance.consentForContent)
return;
if(_requestTimer != nil) {
CLY_LOG_I(@"Already entered for content zone, please exit from content zone first to start again");
return;
}
self.currentTags = tags;
[self fetchContents];;
_requestTimer = [NSTimer scheduledTimerWithTimeInterval:self.requestInterval
target:self
selector:@selector(fetchContents)
userInfo:nil
repeats:YES];
}
- (void)exitContentZone {
[self clearContentState];
}
- (void)changeContent:(NSArray<NSString *> *)tags {
if (![tags isEqualToArray:self.currentTags]) {
[self exitContentZone];
[self enterContentZone:tags];
}
}
#pragma mark - Private Methods
- (void)clearContentState {
[_requestTimer invalidate];
_requestTimer = nil;
[_minuteTimer invalidate];
_minuteTimer = nil;
self.currentTags = nil;
_isRequestQueueLocked = NO;
}
- (void)fetchContents {
if (!CountlyConsentManager.sharedInstance.consentForContent)
return;
if (_isRequestQueueLocked) {
return;
}
_isRequestQueueLocked = YES;
NSURLSessionTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:[self fetchContentsRequest] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
CLY_LOG_I(@"Fetch content details failed: %@", error);
self->_isRequestQueueLocked = NO;
return;
}
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
CLY_LOG_I(@"Failed to parse JSON: %@", jsonError);
self->_isRequestQueueLocked = NO;
return;
}
if (!jsonResponse) {
CLY_LOG_I(@"Received empty or null response.");
self->_isRequestQueueLocked = NO;
return;
}
NSString *pathToHtml = jsonResponse[@"html"];
NSDictionary *placementCoordinates = jsonResponse[@"geo"];
if(pathToHtml) {
[self showContentWithHtmlPath:pathToHtml placementCoordinates:placementCoordinates];
}
self->_isRequestQueueLocked = NO;
}];
[dataTask resume];
}
- (NSURLRequest *)fetchContentsRequest
{
NSString* queryString = [CountlyConnectionManager.sharedInstance queryEssentials];
NSString *resolutionJson = [self resolutionJson];
queryString = [queryString stringByAppendingFormat:@"&%@=%@",
@"resolution", resolutionJson.cly_URLEscaped];
queryString = [CountlyConnectionManager.sharedInstance appendChecksum:queryString];
NSArray *components = [CountlyDeviceInfo.locale componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"_-"]];
queryString = [queryString stringByAppendingFormat:@"&%@=%@",
@"la", components.firstObject];
NSString* URLString = [NSString stringWithFormat:@"%@%@?%@",
CountlyConnectionManager.sharedInstance.host,
kCountlyEndpointContent,
queryString];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
return request;
}
- (NSString *)resolutionJson {
//TODO: check why area is not clickable and safearea things
CGRect screenBounds = [UIScreen mainScreen].bounds;
if (@available(iOS 11.0, *)) {
CGFloat top = UIApplication.sharedApplication.keyWindow.safeAreaInsets.top;
if (top) {
screenBounds.origin.y += top + 5;
screenBounds.size.height -= top + 5;
} else {
screenBounds.origin.y += 20.0;
screenBounds.size.height -= 20.0;
}
} else {
screenBounds.origin.y += 20.0;
screenBounds.size.height -= 20.0;
}
CGFloat width = screenBounds.size.width;
CGFloat height = screenBounds.size.height;
NSDictionary *resolutionDict = @{
@"portrait": @{@"height": @(height), @"width": @(width)},
@"landscape": @{@"height": @(width), @"width": @(height)}
};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resolutionDict options:0 error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (void)showContentWithHtmlPath:(NSString *)urlString placementCoordinates:(NSDictionary *)placementCoordinates {
// Convert pathToHtml to NSURL
NSURL *url = [NSURL URLWithString:urlString];
if (!url || !url.scheme || !url.host) {
NSLog(@"The URL is not valid: %@", urlString);
return;
}
dispatch_async(dispatch_get_main_queue(), ^ {
// Detect screen orientation
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIInterfaceOrientationIsLandscape(orientation);
// Get the appropriate coordinates based on the orientation
NSDictionary *coordinates = isLandscape ? placementCoordinates[@"l"] : placementCoordinates[@"p"];
CGFloat x = [coordinates[@"x"] floatValue];
CGFloat y = [coordinates[@"y"] floatValue];
CGFloat width = [coordinates[@"w"] floatValue];
CGFloat height = [coordinates[@"h"] floatValue];
CGRect frame = CGRectMake(x, y, width, height);
// Log the URL and the frame
CLY_LOG_I(@"Showing content from URL: %@", url);
CLY_LOG_I(@"Placement frame: %@", NSStringFromCGRect(frame));
CountlyWebViewManager* webViewManager = CountlyWebViewManager.new;
[webViewManager createWebViewWithURL:url frame:frame appearBlock:^
{
CLY_LOG_I(@"Webview appeared");
[self clearContentState];
} dismissBlock:^
{
CLY_LOG_I(@"Webview dismissed");
self->_minuteTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
target:self
selector:@selector(enterContentZone)
userInfo:nil
repeats:NO];
if(self.contentCallback) {
self.contentCallback(CLOSED, NSDictionary.new);
}
}];
});
}
#endif
@end