-
Notifications
You must be signed in to change notification settings - Fork 0
/
iRate.m
executable file
·919 lines (788 loc) · 31.1 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//
// iRate.m
//
// Version 1.4.7
//
// Created by Nick Lockwood on 26/01/2011.
// Copyright 2011 Charcoal Design
//
// Distributed under the permissive zlib license
// Get the latest version from either of these locations:
//
// http://charcoaldesign.co.uk/source/cocoa#irate
// https://github.com/nicklockwood/iRate
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
#import "iRate.h"
NSString *const iRateAppStoreGenreGame = @"Games";
static NSString *const iRateRatedVersionKey = @"iRateRatedVersionChecked";
static NSString *const iRateDeclinedVersionKey = @"iRateDeclinedVersion";
static NSString *const iRateLastRemindedKey = @"iRateLastReminded";
static NSString *const iRateLastVersionUsedKey = @"iRateLastVersionUsed";
static NSString *const iRateFirstUsedKey = @"iRateFirstUsed";
static NSString *const iRateUseCountKey = @"iRateUseCount";
static NSString *const iRateEventCountKey = @"iRateEventCount";
static NSString *const iRateMacAppStoreBundleID = @"com.apple.appstore";
static NSString *const iRateAppLookupURLFormat = @"http://itunes.apple.com/lookup?country=%@";
//note, these don't link directly to the review page - there doesn't seem to be a way to do that
static NSString *const iRateiOSAppStoreURLFormat = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%i";
static NSString *const iRateMacAppStoreURLFormat = @"macappstore://itunes.apple.com/app/id%i";
#define SECONDS_IN_A_DAY 86400.0
#define MAC_APP_STORE_REFRESH_DELAY 5.0
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
@interface iRate() <UIAlertViewDelegate>
#else
@interface iRate()
#endif
@property (nonatomic, strong) id visibleAlert;
@property (nonatomic, assign) int previousOrientation;
@end
@implementation iRate
@synthesize appStoreID = _appStoreID;
@synthesize appStoreGenre = _appStoreGenre;
@synthesize appStoreCountry = _appStoreCountry;
@synthesize applicationName = _applicationName;
@synthesize applicationVersion = _applicationVersion;
@synthesize applicationBundleID = _applicationBundleID;
@synthesize daysUntilPrompt = _daysUntilPrompt;
@synthesize usesUntilPrompt = _usesUntilPrompt;
@synthesize eventsUntilPrompt = _eventsUntilPrompt;
@synthesize remindPeriod = _remindPeriod;
@synthesize messageTitle = _messageTitle;
@synthesize message = _message;
@synthesize cancelButtonLabel = _cancelButtonLabel;
@synthesize remindButtonLabel = _remindButtonLabel;
@synthesize rateButtonLabel = _rateButtonLabel;
@synthesize ratingsURL = _ratingsURL;
@synthesize disableAlertViewResizing = _disableAlertViewResizing;
@synthesize onlyPromptIfLatestVersion = _onlyPromptIfLatestVersion;
@synthesize onlyPromptIfMainWindowIsAvailable = _onlyPromptIfMainWindowIsAvailable;
@synthesize promptAtLaunch = _promptAtLaunch;
@synthesize debug = _debug;
@synthesize delegate = _delegate;
@synthesize visibleAlert = _visibleAlert;
@synthesize previousOrientation = _previousOrientation;
#pragma mark -
#pragma mark Lifecycle methods
+ (void)load
{
@autoreleasepool
{
//initialise iRate
[iRate sharedInstance];
}
}
+ (iRate *)sharedInstance
{
static iRate *sharedInstance = nil;
if (sharedInstance == nil)
{
sharedInstance = [[iRate alloc] init];
}
return sharedInstance;
}
- (NSString *)localizedStringForKey:(NSString *)key
{
static NSBundle *bundle = nil;
if (bundle == nil)
{
//get localisation bundle
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"iRate" ofType:@"bundle"];
bundle = [NSBundle bundleWithPath:bundlePath] ?: [NSBundle mainBundle];
//get correct lproj folder as this doesn't always happen automatically
for (NSString *language in [NSLocale preferredLanguages])
{
if ([[bundle localizations] containsObject:language])
{
bundlePath = [bundle pathForResource:language ofType:@"lproj"];
bundle = [NSBundle bundleWithPath:bundlePath];
break;
}
}
//retain bundle
bundle = AH_RETAIN(bundle);
}
//return localised string
return [bundle localizedStringForKey:key value:nil table:nil];
}
- (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];
}
self.previousOrientation = [UIApplication sharedApplication].statusBarOrientation;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(willRotate)
name:UIDeviceOrientationDidChangeNotification
object:nil];
#else
//register for mac application events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationLaunched:)
name:NSApplicationDidFinishLaunchingNotification
object:nil];
#endif
//get country
self.appStoreCountry = [(NSLocale *)[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
//application version (use short version preferentially)
self.applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if ([self.applicationVersion length] == 0)
{
self.applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
}
//localised application name
self.applicationName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if ([self.applicationName length] == 0)
{
self.applicationName = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
}
//bundle id
self.applicationBundleID = [[NSBundle mainBundle] bundleIdentifier];
//usage settings - these have sensible defaults
self.onlyPromptIfLatestVersion = YES;
self.onlyPromptIfMainWindowIsAvailable = YES;
self.promptAtLaunch = YES;
self.usesUntilPrompt = 10;
self.eventsUntilPrompt = 10;
self.daysUntilPrompt = 10.0f;
self.remindPeriod = 1.0f;
//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 = [self localizedStringForKey:@"No, Thanks"];
self.remindButtonLabel = [self localizedStringForKey:@"Remind Me Later"];
self.rateButtonLabel = [self localizedStringForKey:@"Rate It Now"];
}
return self;
}
- (id<iRateDelegate>)delegate
{
if (_delegate == nil)
{
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
_delegate = (id<iRateDelegate>)[[UIApplication sharedApplication] delegate];
#else
_delegate = (id<iRateDelegate>)[[NSApplication sharedApplication] delegate];
#endif
}
return _delegate;
}
- (NSString *)messageTitle
{
if (_messageTitle)
{
return _messageTitle;
}
return [NSString stringWithFormat:[self localizedStringForKey:@"Rate %@"], self.applicationName];
}
- (NSString *)message
{
if (_message)
{
return _message;
}
if ([self.appStoreGenre isEqualToString:iRateAppStoreGenreGame])
{
return [NSString stringWithFormat:[self localizedStringForKey:@"If you enjoy playing %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!"], self.applicationName];
}
else
{
return [NSString stringWithFormat:[self localizedStringForKey:@"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!"], self.applicationName];
}
}
- (NSURL *)ratingsURL
{
if (_ratingsURL)
{
return _ratingsURL;
}
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
return [NSURL URLWithString:[NSString stringWithFormat:iRateiOSAppStoreURLFormat, self.appStoreID]];
#else
return [NSURL URLWithString:[NSString stringWithFormat:iRateMacAppStoreURLFormat, self.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:self.applicationVersion];
}
- (void)setDeclinedThisVersion:(BOOL)declined
{
[[NSUserDefaults standardUserDefaults] setObject:(declined? self.applicationVersion: nil) forKey:iRateDeclinedVersionKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)ratedThisVersion
{
return [[[NSUserDefaults standardUserDefaults] objectForKey:iRateRatedVersionKey] isEqualToString:self.applicationVersion];
}
- (void)setRatedThisVersion:(BOOL)rated
{
[[NSUserDefaults standardUserDefaults] setObject:(rated? self.applicationVersion: nil) forKey:iRateRatedVersionKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
AH_RELEASE(_appStoreGenre);
AH_RELEASE(_appStoreCountry);
AH_RELEASE(_applicationName);
AH_RELEASE(_applicationVersion);
AH_RELEASE(_applicationBundleID);
AH_RELEASE(_messageTitle);
AH_RELEASE(_message);
AH_RELEASE(_cancelButtonLabel);
AH_RELEASE(_remindButtonLabel);
AH_RELEASE(_rateButtonLabel);
AH_RELEASE(_ratingsURL);
AH_RELEASE(_visibleAlert);
AH_SUPER_DEALLOC;
}
#pragma mark -
#pragma mark Methods
- (void)incrementUseCount
{
self.usesCount ++;
}
- (void)incrementEventCount
{
self.eventCount ++;
}
- (BOOL)shouldPromptForRating
{
//debug mode?
if (self.debug)
{
return YES;
}
//check if we've rated this version
else if (self.ratedThisVersion)
{
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.daysUntilPrompt > 0.0f && self.firstUsed == nil) || [[NSDate date] timeIntervalSinceDate:self.firstUsed] < self.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 < self.usesUntilPrompt && self.eventCount < self.eventsUntilPrompt)
{
return NO;
}
//check if within the reminder period
else if (self.lastReminded != nil && [[NSDate date] timeIntervalSinceDate:self.lastReminded] < self.remindPeriod * SECONDS_IN_A_DAY)
{
return NO;
}
//lets prompt!
return YES;
}
- (NSString *)valueForKey:(NSString *)key inJSON:(NSString *)json
{
NSRange keyRange = [json rangeOfString:[NSString stringWithFormat:@"\"%@\"", key]];
if (keyRange.location != NSNotFound)
{
NSInteger start = keyRange.location + keyRange.length;
NSRange valueStart = [json rangeOfString:@":" options:0 range:NSMakeRange(start, [json length] - start)];
if (valueStart.location != NSNotFound)
{
start = valueStart.location + 1;
NSRange valueEnd = [json rangeOfString:@"," options:0 range:NSMakeRange(start, [json length] - start)];
if (valueEnd.location != NSNotFound)
{
NSString *value = [json substringWithRange:NSMakeRange(start, valueEnd.location - start)];
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
while ([value hasPrefix:@"\""] && ![value hasSuffix:@"\""])
{
if (valueEnd.location == NSNotFound)
{
break;
}
NSInteger newStart = valueEnd.location + 1;
valueEnd = [json rangeOfString:@"," options:0 range:NSMakeRange(newStart, [json length] - newStart)];
value = [json substringWithRange:NSMakeRange(start, valueEnd.location - start)];
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
value = [value stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
value = [value stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
value = [value stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
value = [value stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
value = [value stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
value = [value stringByReplacingOccurrencesOfString:@"\\r" withString:@"\r"];
value = [value stringByReplacingOccurrencesOfString:@"\\t" withString:@"\t"];
value = [value stringByReplacingOccurrencesOfString:@"\\f" withString:@"\f"];
value = [value stringByReplacingOccurrencesOfString:@"\\b" withString:@"\f"];
while (YES)
{
NSRange unicode = [value rangeOfString:@"\\u"];
if (unicode.location == NSNotFound)
{
break;
}
uint32_t c = 0;
NSString *hex = [value substringWithRange:NSMakeRange(unicode.location + 2, 4)];
NSScanner *scanner = [NSScanner scannerWithString:hex];
[scanner scanHexInt:&c];
if (c <= 0xffff)
{
value = [value stringByReplacingCharactersInRange:NSMakeRange(unicode.location, 6) withString:[NSString stringWithFormat:@"%C", (unichar)c]];
}
else
{
//convert character to surrogate pair
uint16_t x = (uint16_t)c;
uint16_t u = (c >> 16) & ((1 << 5) - 1);
uint16_t w = (uint16_t)u - 1;
unichar high = 0xd800 | (w << 6) | x >> 10;
unichar low = (uint16_t)(0xdc00 | (x & ((1 << 10) - 1)));
value = [value stringByReplacingCharactersInRange:NSMakeRange(unicode.location, 6) withString:[NSString stringWithFormat:@"%C%C", high, low]];
}
}
return value;
}
}
}
return nil;
}
- (void)setAppStoreIDOnMainThread:(NSString *)appStoreIDString
{
self.appStoreID = (NSUInteger)[appStoreIDString longLongValue];
}
- (void)connectionSucceeded
{
//confirm with delegate
if ([self.delegate respondsToSelector:@selector(iRateShouldPromptForRating)])
{
if (![self.delegate iRateShouldPromptForRating])
{
return;
}
}
//prompt user
[self promptForRating];
}
- (void)connectionError:(NSError *)error
{
//could not connect
if ([self.delegate respondsToSelector:@selector(iRateCouldNotConnectToAppStore:)])
{
[self.delegate iRateCouldNotConnectToAppStore:error];
}
}
- (void)checkForConnectivityInBackground
{
@synchronized (self)
{
@autoreleasepool
{
//first check iTunes
NSString *iTunesServiceURL = [NSString stringWithFormat:iRateAppLookupURLFormat, self.appStoreCountry];
if (self.appStoreID)
{
iTunesServiceURL = [iTunesServiceURL stringByAppendingFormat:@"&id=%i", self.appStoreID];
}
else
{
iTunesServiceURL = [iTunesServiceURL stringByAppendingFormat:@"&bundleId=%@", self.applicationBundleID];
}
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iTunesServiceURL] options:NSDataReadingUncached error:&error];
if (data)
{
//convert to string
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//check bundle ID matches
NSString *bundleID = [self valueForKey:@"bundleId" inJSON:json];
if ((bundleID && [bundleID isEqualToString:self.applicationBundleID]) || self.debug)
{
//get genre
if (!self.appStoreGenre)
{
[self performSelectorOnMainThread:@selector(setAppStoreGenre:) withObject:[self valueForKey:@"primaryGenreName" inJSON:json] waitUntilDone:YES];
}
//get app id
if (!self.appStoreID)
{
NSString *appStoreIDString = [self valueForKey:@"trackId" inJSON:json];
[self performSelectorOnMainThread:@selector(setAppStoreIDOnMainThread:) withObject:appStoreIDString waitUntilDone:YES];
}
//check version
if (self.onlyPromptIfLatestVersion && !self.debug)
{
NSString *latestVersion = [self valueForKey:@"version" inJSON:json];
if ([latestVersion compare:self.applicationVersion options:NSNumericSearch] == NSOrderedDescending)
{
error = [NSError errorWithDomain:@"iRate" code:1 userInfo:[NSDictionary dictionaryWithObject:@"Installed app is not the latest version available" forKey:NSLocalizedDescriptionKey]];
}
}
}
else
{
error = [NSError errorWithDomain:@"iRate" code:2 userInfo:[NSDictionary dictionaryWithObject:@"Service bundleID and applicationBundleID did not match" forKey:NSLocalizedDescriptionKey]];
}
//release json
AH_RELEASE(json);
}
if (error)
{
[self performSelectorOnMainThread:@selector(connectionError:) withObject:error waitUntilDone:YES];
}
else if (self.appStoreID || self.debug)
{
//show prompt
[self performSelectorOnMainThread:@selector(connectionSucceeded) withObject:nil waitUntilDone:YES];
}
}
}
}
- (void)promptIfNetworkAvailable
{
[self performSelectorInBackground:@selector(checkForConnectivityInBackground) withObject:nil];
}
- (void)promptForRating
{
if (!self.visibleAlert)
{
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:self.messageTitle
message:self.message
delegate:self
cancelButtonTitle:self.cancelButtonLabel
otherButtonTitles:self.rateButtonLabel, nil];
if (self.remindButtonLabel)
{
[alert addButtonWithTitle:self.remindButtonLabel];
}
self.visibleAlert = alert;
[self.visibleAlert show];
AH_RELEASE(alert);
#else
//only show when main window is available
if (self.onlyPromptIfMainWindowIsAvailable && ![[NSApplication sharedApplication] mainWindow])
{
[self performSelector:@selector(promptForRating) withObject:nil afterDelay:0.5];
return;
}
self.visibleAlert = [NSAlert alertWithMessageText:self.messageTitle
defaultButton:self.rateButtonLabel
alternateButton:self.cancelButtonLabel
otherButton:nil
informativeTextWithFormat:@"%@", self.message];
if (self.remindButtonLabel)
{
[self.visibleAlert addButtonWithTitle:self.remindButtonLabel];
}
[self.visibleAlert beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow]
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
#endif
}
}
- (void)applicationLaunched:(NSNotification *)notification
{
//check if this is a new version
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![[defaults objectForKey:iRateLastVersionUsedKey] isEqualToString:self.applicationVersion])
{
//reset counts
[defaults setObject:self.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];
//inform about app update
if ([self.delegate respondsToSelector:@selector(iRateDidDetectAppUpdate)])
{
[self.delegate iRateDidDetectAppUpdate];
}
}
[self incrementUseCount];
if (self.promptAtLaunch && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (void)applicationWillEnterForeground:(NSNotification *)notification
{
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
[self incrementUseCount];
if (self.promptAtLaunch && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
}
#endif
#pragma mark -
#pragma mark UIAlertView methods
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (void)openRatingsPageInAppStore
{
[[UIApplication sharedApplication] openURL:self.ratingsURL];
}
- (void)resizeAlertView:(UIAlertView *)alertView
{
if (!self.disableAlertViewResizing)
{
NSInteger imageCount = 0;
CGFloat offset = 0.0f;
CGFloat messageOffset = 0.0f;
for (UIView *view in alertView.subviews)
{
CGRect frame = view.frame;
if ([view isKindOfClass:[UILabel class]])
{
UILabel *label = (UILabel *)view;
if ([label.text isEqualToString:alertView.title])
{
[label sizeToFit];
offset = label.frame.size.height - fmax(0.0f, 45.f - label.frame.size.height);
if (label.frame.size.height > frame.size.height)
{
offset = messageOffset = label.frame.size.height - frame.size.height;
frame.size.height = label.frame.size.height;
}
}
else if ([label.text isEqualToString:alertView.message])
{
label.alpha = 1.0f;
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
[label sizeToFit];
offset += label.frame.size.height - frame.size.height;
frame.origin.y += messageOffset;
frame.size.height = label.frame.size.height;
}
}
else if ([view isKindOfClass:[UITextView class]])
{
view.alpha = 0.0f;
}
else if ([view isKindOfClass:[UIImageView class]])
{
if (imageCount++ > 0)
{
view.alpha = 0.0f;
}
}
else if ([view isKindOfClass:[UIControl class]])
{
frame.origin.y += offset;
}
view.frame = frame;
}
CGRect frame = alertView.frame;
frame.origin.y -= roundf(offset/2.0f);
frame.size.height += offset;
alertView.frame = frame;
}
}
- (void)willRotate
{
[self performSelectorOnMainThread:@selector(didRotate) withObject:nil waitUntilDone:NO];
}
- (void)didRotate
{
if (self.previousOrientation != [UIApplication sharedApplication].statusBarOrientation)
{
self.previousOrientation = [UIApplication sharedApplication].statusBarOrientation;
[self resizeAlertView:self.visibleAlert];
}
}
- (void)willPresentAlertView:(UIAlertView *)alertView
{
[self resizeAlertView:alertView];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
//consider cancel button presence
if (alertView.cancelButtonIndex == -1) {
++buttonIndex;
}
if (buttonIndex == alertView.cancelButtonIndex)
{
//ignore this version
self.declinedThisVersion = YES;
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidDeclineToRateApp)])
{
[self.delegate iRateUserDidDeclineToRateApp];
}
}
else if (buttonIndex == 2)
{
//remind later
self.lastReminded = [NSDate date];
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidRequestReminderToRateApp)])
{
[self.delegate iRateUserDidRequestReminderToRateApp];
}
}
else
{
//mark as rated
self.ratedThisVersion = YES;
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidAttemptToRateApp)])
{
[self.delegate iRateUserDidAttemptToRateApp];
}
//go to ratings page
[self openRatingsPageInAppStore];
}
//release alert
self.visibleAlert = 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.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;
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidDeclineToRateApp)])
{
[self.delegate iRateUserDidDeclineToRateApp];
}
break;
}
case NSAlertDefaultReturn:
{
//mark as rated
self.ratedThisVersion = YES;
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidAttemptToRateApp)])
{
[self.delegate iRateUserDidAttemptToRateApp];
}
//launch mac app store
[self openRatingsPageInAppStore];
break;
}
default:
{
//remind later
self.lastReminded = [NSDate date];
//log event
if ([self.delegate respondsToSelector:@selector(iRateUserDidRequestReminderToRateApp)])
{
[self.delegate iRateUserDidRequestReminderToRateApp];
}
}
}
//release alert
self.visibleAlert = nil;
}
#endif
- (void)logEvent:(BOOL)deferPrompt
{
[self incrementEventCount];
if (!deferPrompt && [self shouldPromptForRating])
{
[self promptIfNetworkAvailable];
}
}
@end