summaryrefslogtreecommitdiff
path: root/Juick/AppDelegate.m
blob: 47c18ef5b44593486056909cb6912db4d4191e7a (plain) (blame)
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
//
//  AppDelegate.m
//  Juick
//
//  Created by Vitaly Takmazov on 26.10.13.
//  Copyright (c) 2013 com.juick. All rights reserved.
//

#import "MessagesViewController.h"
#import "LoginViewController.h"

#import "Message.h"
#import "User.h"
#import "DeviceRegistration.h"
#import "NewPostViewController.h"
#import "FeedViewController.h"
#import "NSData+Hex.h"

NSString * const UserUpdatedNotificationName = @"UserUpdated";

@interface AppDelegate()
-(void) parseNotificationPayload:(NSDictionary *)userInfo;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.api = [API new];
    self.sharedDateFormatter = [NSDateFormatter new];
    self.sharedDateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [self.sharedDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [[UINavigationBar appearance] setTintColor:[UIColor colorNamed:@"Title"]];
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorNamed:@"Background"]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorNamed:@"Muted"]}];
    [[UINavigationBar appearance] setLargeTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorNamed:@"Muted"]}];
    [[UIToolbar appearance] setTintColor:[UIColor colorNamed:@"Title"]];
    [[UITabBar appearance] setTintColor:[UIColor colorNamed:@"Title"]];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
#if !TARGET_IPHONE_SIMULATOR
    [self registerForRemoteNotifications];
#endif
    NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [self parseNotificationPayload:userInfo];
    }
    return YES;
}

- (void)registerForRemoteNotifications {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
        if (!error) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            }];
        }
    }];
}

-(void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [deviceToken hexString];
    [[NSOperationQueue new] addOperationWithBlock:^{
        DeviceRegistration *registration = [DeviceRegistration new];
        registration.type = @"apns";
        registration.token = token;
        [self.api refreshDeviceRegistration:registration callback:^(BOOL success) {
            if (success) {
                NSLog(@"successfully refreshed registration with %@", token);
            }
        }];
    }];
}

-(void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Error: %@", [error debugDescription]);
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    [self parseNotificationPayload:userInfo];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        UITabBarController *main = (UITabBarController *)[self navigator];
        if ([self.pushedThread integerValue] > 0) {
            [main setSelectedIndex:0];
            MessagesViewController *discover = (MessagesViewController *)[main.viewControllers objectAtIndex:0];
            [discover viewThreadForMessage:nil mid:self.pushedThread scrollTo:self.pushedReplyId];
            [self cleanupPushedData];
        } else {
            [main setSelectedIndex:2];
            MessagesViewController *dialogs = (MessagesViewController *)[main.viewControllers objectAtIndex:2];
            [dialogs performSegueWithIdentifier:@"chatSegue" sender:dialogs];
        }
    }];
    completionHandler();
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if (userInfo[@"service"]) {
        User *user = [User fromJSON:userInfo[@"user"]];
        application.applicationIconBadgeNumber = user.unreadCount;
        UITabBarController *main = (UITabBarController *)[self navigator];
        UIViewController *discussions = [main.viewControllers objectAtIndex:1];
        if (user.unreadCount > 0) {
            [discussions tabBarItem].badgeColor = [UIColor colorNamed:@"Funny"];
            [discussions tabBarItem].badgeValue = [NSString stringWithFormat:@"%ld", user.unreadCount];
        } else {
            [discussions tabBarItem].badgeValue = nil;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:UserUpdatedNotificationName object:user];
        [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
            for (UNNotification* notification in notifications) {
                if ([notification.request.content.userInfo[@"mid"] integerValue] == [userInfo[@"mid"] integerValue]) {
                    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
                }
            }
        }];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

-(void) parseNotificationPayload:(NSDictionary *)userInfo {
    self.pushedThread = userInfo[@"mid"];
    self.pushedUname = userInfo[@"uname"];
    self.pushedReplyId = userInfo[@"rid"];
}

-(void) cleanupPushedData {
    self.pushedUname = nil;
    self.pushedThread = nil;
    self.pushedReplyId = nil;
}

+(AppDelegate *) shared {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (UINavigationController *) navigator {
    return [[(UINavigationController *)self.window.rootViewController viewControllers] firstObject];
}

- (void)presentThread:(UIViewController *)vc {
    [[self navigator] performSegueWithIdentifier:@"threadSegue" sender:vc];
}

- (void) presentEditor:(UIViewController *)vc {
    [[self navigator] performSegueWithIdentifier:@"editorSegue" sender:vc];
}

- (void) presentLoginView:(UIViewController *)vc {
    [[self navigator] performSegueWithIdentifier:@"loginSegue" sender:vc];
}

- (void)unauthorized {
    [self presentLoginView:self.window.rootViewController];
}

@end