-
Notifications
You must be signed in to change notification settings - Fork 3
/
iRate.m
512 lines (423 loc) · 12.8 KB
/
iRate.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//
// iRate.m
// iRate
//
// Created by Nick Lockwood on 26/01/2011.
// Copyright 2011 Charcoal Design. All rights reserved.
//
#import "iRate.h"
#import "Notifications.h"
NSString * const iRateRatedVersionKey = @"iRateRatedVersionChecked";
NSString * const iRateDeclinedVersionKey = @"iRateDeclinedVersion";
NSString * const iRateLastRemindedKey = @"iRateLastReminded";
NSString * const iRateLastVersionUsedKey = @"iRateLastVersionUsed";
NSString * const iRateFirstUsedKey = @"iRateFirstUsed";
NSString * const iRateUseCountKey = @"iRateUseCount";
NSString * const iRateEventCountKey = @"iRateEventCount";
NSString * const iRateMacAppStoreBundleID = @"com.apple.appstore";
NSString * const iRateiOSAppStoreURLFormat = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%i";
NSString * const iRateMacAppStoreURLFormat = @"macappstore://itunes.apple.com/app/id%i";
static iRate *sharedInstance = nil;
#define SECONDS_IN_A_DAY 86400.0
#define MAC_APP_STORE_REFRESH_DELAY 5
@interface iRate()
@property (nonatomic, retain) NSString *applicationVersion;
@end
@implementation iRate
@synthesize appStoreID;
@synthesize applicationName;
@synthesize applicationVersion;
@synthesize daysUntilPrompt;
@synthesize usesUntilPrompt;
@synthesize eventsUntilPrompt;
@synthesize remindPeriod;
@synthesize messageTitle;
@synthesize message;
@synthesize cancelButtonLabel;
@synthesize remindButtonLabel;
@synthesize rateButtonLabel;
@synthesize ratingsURL;
@synthesize disabled;
@synthesize debug;
@synthesize delegate;
#pragma mark -
#pragma mark Lifecycle methods
+ (iRate *)sharedInstance
{
if (sharedInstance == nil)
{
sharedInstance = [[iRate alloc] init];
}
return sharedInstance;
}
- (iRate *)init
{
if ((self = [super init]))
{
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
//register for iphone application events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationLaunched:)
name:UIApplicationDidFinishLaunchingNotification
object:nil];
if (&UIApplicationWillEnterForegroundNotification)
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
#else
//register for mac application events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationLaunched:)
name:NSApplicationDidFinishLaunchingNotification
object:nil];
#endif
//application name and version
self.applicationName = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
self.applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
//usage settings - these have sensible defaults
usesUntilPrompt = 10;
eventsUntilPrompt = 10;
daysUntilPrompt = 10;
remindPeriod = 1;
//message text, you may wish to customise these, e.g. for localisation
self.messageTitle = nil; //set lazily so that appname can be included
self.message = nil; //set lazily so that appname can be included
self.cancelButtonLabel = @"No, Thanks";
self.remindButtonLabel = @"Remind Me Later";
self.rateButtonLabel = @"Rate It Now";
}
return self;
}
- (NSString *)messageTitle
{
if (messageTitle)
{
return messageTitle;
}
return [NSString stringWithFormat:@"Rate %@", applicationName];
}
- (NSString *)message
{
if (message)
{
return message;
}
return [NSString stringWithFormat:@"If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!", applicationName];
}
- (NSURL *)ratingsURL
{
if (ratingsURL)
{
return ratingsURL;
}
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
return [NSURL URLWithString:[NSString stringWithFormat:iRateiOSAppStoreURLFormat, appStoreID]];
#else
return [NSURL URLWithString:[NSString stringWithFormat:iRateMacAppStoreURLFormat, appStoreID]];
#endif
}
- (NSDate *)firstUsed
{
return [[NSUserDefaults standardUserDefaults] objectForKey:iRateFirstUsedKey];
}
- (void)setFirstUsed:(NSDate *)date
{
[[NSUserDefaults standardUserDefaults] setObject:date forKey:iRateFirstUsedKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSDate *)lastReminded
{
return [[NSUserDefaults standardUserDefaults] objectForKey:iRateLastRemindedKey];
}
- (void)setLastReminded:(NSDate *)date
{
[[NSUserDefaults standardUserDefaults] setObject:date forKey:iRateLastRemindedKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSUInteger)usesCount
{
return [[NSUserDefaults standardUserDefaults] integerForKey:iRateUseCountKey];
}
- (void)setUsesCount:(NSUInteger)count
{
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:iRateUseCountKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSUInteger)eventCount;
{
return [[NSUserDefaults standardUserDefaults] integerForKey:iRateEventCountKey];
}
- (void)setEventCount:(NSUInteger)count
{
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:iRateEventCountKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)declinedThisVersion
{
return [[[NSUserDefaults standardUserDefaults] objectForKey:iRateDeclinedVersionKey] isEqualToString:applicationVersion];
}
- (void)setDeclinedThisVersion:(BOOL)declined
{
[[NSUserDefaults standardUserDefaults] setObject:(declined? applicationVersion: nil) forKey:iRateDeclinedVersionKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)ratedThisVersion
{
return [[[NSUserDefaults standardUserDefaults] objectForKey:iRateRatedVersionKey] isEqualToString:applicationVersion];
}
- (void)setRatedThisVersion:(BOOL)rated
{
[[NSUserDefaults standardUserDefaults] setObject:(rated? applicationVersion: nil) forKey:iRateRatedVersionKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[applicationName release];
[applicationVersion release];
[messageTitle release];
[message release];
[cancelButtonLabel release];
[remindButtonLabel release];
[rateButtonLabel release];
[ratingsURL release];
[super dealloc];
}
#pragma mark -
#pragma mark Methods
- (void)incrementUseCount
{
self.usesCount ++;
}
- (void)incrementEventCount
{
self.eventCount ++;
}
- (BOOL)shouldPromptForRating
{
NSLog(@"iRate: eventCount = %d (eventsUntilPrompt=%d)", self.eventCount, eventsUntilPrompt);
//debug mode?
if (debug)
{
return YES;
}
//check if we've rated this version
else if (self.ratedThisVersion)
{
NSLog(@"iRate: user has already rated this version");
return NO;
}
//check if we've declined to rate this version
else if (self.declinedThisVersion)
{
return NO;
}
//check how long we've been using this version
else if (self.firstUsed == nil || [[NSDate date] timeIntervalSinceDate:self.firstUsed] < daysUntilPrompt * SECONDS_IN_A_DAY)
{
return NO;
}
//check how many times we've used it and the number of significant events
else if (self.usesCount < usesUntilPrompt && self.eventCount < eventsUntilPrompt)
{
return NO;
}
//check if within the reminder period
else if (self.lastReminded != nil && [[NSDate date] timeIntervalSinceDate:self.lastReminded] < remindPeriod * SECONDS_IN_A_DAY)
{
return NO;
}
//lets prompt!
return YES;
}
- (void)promptForRating
{
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:self.messageTitle
message:self.message
delegate:self
cancelButtonTitle:cancelButtonLabel
otherButtonTitles:rateButtonLabel, nil];
if (remindButtonLabel)
{
[alert addButtonWithTitle:remindButtonLabel];
}
[alert show];
[alert release];
#else
//only show when main window is available
if (![[NSApplication sharedApplication] mainWindow])
{
[self performSelector:@selector(promptForRating) withObject:nil afterDelay:0.5];
return;
}
NSAlert *alert = [NSAlert alertWithMessageText:self.messageTitle
defaultButton:rateButtonLabel
alternateButton:cancelButtonLabel
otherButton:nil
informativeTextWithFormat:self.message];
if (remindButtonLabel)
{
[alert addButtonWithTitle:remindButtonLabel];
}
[alert beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow]
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
#endif
}
- (void)promptIfNetworkAvailable
{
//test for app store connectivity the simplest, most reliable way - by accessing apple.com
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://apple.com"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
//send request
[[NSURLConnection connectionWithRequest:request delegate:self] start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//good enough; don't download any more data
[connection cancel];
//confirm with delegate
if ([(NSObject *)delegate respondsToSelector:@selector(iRateShouldShouldPromptForRating)])
{
if (![delegate iRateShouldShouldPromptForRating])
{
return;
}
}
//prompt user
[self promptForRating];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//could not connect
if ([(NSObject *)delegate respondsToSelector:@selector(iRateCouldNotConnectToAppStore:)])
{
[delegate iRateCouldNotConnectToAppStore:error];
}
}
- (void)applicationLaunched:(NSNotification *)notification
{
//check if this is a new version
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![[defaults objectForKey:iRateLastVersionUsedKey] isEqualToString:applicationVersion])
{
//reset counts
[defaults setObject:applicationVersion forKey:iRateLastVersionUsedKey];
[defaults setObject:[NSDate date] forKey:iRateFirstUsedKey];
[defaults setInteger:0 forKey:iRateUseCountKey];
[defaults setInteger:0 forKey:iRateEventCountKey];
[defaults setObject:nil forKey:iRateLastRemindedKey];
[defaults synchronize];
}
[self incrementUseCount];
if (!disabled && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
- (void)applicationWillEnterForeground:(NSNotification *)notification
{
[self incrementUseCount];
if (!disabled && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
#pragma mark -
#pragma mark UIAlertViewDelegate methods
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (void)openRatingsPageInAppStore
{
NSLog(@"opening ratings url: %@", self.ratingsURL);
[[UIApplication sharedApplication] openURL:self.ratingsURL];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == alertView.cancelButtonIndex)
{
//ignore this version
self.declinedThisVersion = YES;
}
else if (buttonIndex == 2)
{
//remind later
self.lastReminded = [NSDate date];
}
else
{
//mark as rated
self.ratedThisVersion = YES;
//go to ratings page
[self openRatingsPageInAppStore];
}
// BDE: let the app know when the dialog is actually dismissed. seems like common
// courtesy, no?
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DONE_APP_RATINGS object:nil];
}
#else
- (void)openAppPageWhenAppStoreLaunched
{
//check if app store is running
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
while (GetNextProcess(&psn) == noErr)
{
CFDictionaryRef cfDict = ProcessInformationCopyDictionary(&psn, kProcessDictionaryIncludeAllInformationMask);
NSString *bundleID = [(NSDictionary *)cfDict objectForKey:(NSString *)kCFBundleIdentifierKey];
if ([iRateMacAppStoreBundleID isEqualToString:bundleID])
{
//open app page
[[NSWorkspace sharedWorkspace] performSelector:@selector(openURL:) withObject:self.ratingsURL afterDelay:MAC_APP_STORE_REFRESH_DELAY];
CFRelease(cfDict);
return;
}
CFRelease(cfDict);
}
//try again
[self performSelector:@selector(openAppPageWhenAppStoreLaunched) withObject:nil afterDelay:0];
}
- (void)openRatingsPageInAppStore
{
[[NSWorkspace sharedWorkspace] openURL:self.ratingsURL];
[self openAppPageWhenAppStoreLaunched];
}
- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
switch (returnCode)
{
case NSAlertAlternateReturn:
{
//ignore this version
self.declinedThisVersion = YES;
break;
}
case NSAlertDefaultReturn:
{
//mark as rated
self.ratedThisVersion = YES;
//launch mac app store
[self openRatingsPageInAppStore];
break;
}
default:
{
//remind later
self.lastReminded = [NSDate date];
}
}
}
#endif
- (void)logEvent:(BOOL)deferPrompt
{
[self incrementEventCount];
if (!deferPrompt && !disabled && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
@end