summaryrefslogtreecommitdiff
path: root/JuickPush/NotificationService.m
blob: afeec5534d503eebbacd6a0e4f7b5b688d81d0e9 (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
//
//  NotificationService.m
//  JuickPush
//
//  Created by Vitaly Takmazov on 18/10/2018.
//  Copyright © 2018 com.juick. All rights reserved.
//

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    NSURL *avatarURL = [NSURL URLWithString:request.content.userInfo[@"avatarUrl"]];
    
    NSURLSession* downloadSession = [NSURLSession sharedSession];
    
    [[downloadSession downloadTaskWithURL:avatarURL completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            NSError *err = nil;
            NSString *temporaryDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:[response suggestedFilename]];
            [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:temporaryDirectory error:&err];
            UNNotificationAttachment *avatarAttachment = [UNNotificationAttachment attachmentWithIdentifier:avatarURL.lastPathComponent URL:[NSURL fileURLWithPath:temporaryDirectory] options:nil error:&err];
            self.bestAttemptContent.attachments = @[avatarAttachment];
            self.contentHandler(self.bestAttemptContent);
        }
    }] resume];
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end