美文网首页
远程推送和后台数据获取

远程推送和后台数据获取

作者: liboxiang | 来源:发表于2018-05-31 22:53 被阅读24次

详情:https://www.objc.io/issues/5-ios7/multitasking/

Background Fetch

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

    return YES;
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

    NSURL *url = [[NSURL alloc] initWithString:@"http://yourserver.com/data.json"];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url 
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error) {
            completionHandler(UIBackgroundFetchResultFailed);
            return;
        }

        // Parse response/data and determine whether new content was available
        BOOL hasNewData = ...
        if (hasNewData) {
            completionHandler(UIBackgroundFetchResultNewData);
        } else {
            completionHandler(UIBackgroundFetchResultNoData);
        }
    }];

    // Start the task
    [task resume];
}

远程推送

推送内容结构
{
    "aps" : {
        "content-available" : 1
    },
    "content-id" : 42
}
实现
SELECT ALL
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"Remote Notification userInfo is %@", userInfo);

    NSNumber *contentID = userInfo[@"content-id"];
    // Do something with the content ID
    completionHandler(UIBackgroundFetchResultNewData);
}

后台网络请求

- (NSURLSession *)backgroundURLSession
{
    static NSURLSession *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *identifier = @"io.objc.backgroundTransferExample";
        NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
        session = [NSURLSession sessionWithConfiguration:sessionConfig 
                                                delegate:self 
                                           delegateQueue:[NSOperationQueue mainQueue]];
    });

    return session;
}

- (void)           application:(UIApplication *)application 
  didReceiveRemoteNotification:(NSDictionary *)userInfo 
        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"Received remote notification with userInfo %@", userInfo);

    NSNumber *contentID = userInfo[@"content-id"];
    NSString *downloadURLString = [NSString stringWithFormat:@"http://yourserver.com/downloads/%d.mp3", [contentID intValue]];
    NSURL* downloadURL = [NSURL URLWithString:downloadURLString];

    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
    NSURLSessionDownloadTask *task = [[self backgroundURLSession] downloadTaskWithRequest:request];
    task.taskDescription = [NSString stringWithFormat:@"Podcast Episode %d", [contentID intValue]];
    [task resume];

    completionHandler(UIBackgroundFetchResultNewData);
}

当网络请求完成的时候,如果app还处于后台状态,需要实现下面代码

- (void)application:(UIApplication *)application 
  handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
    // You must re-establish a reference to the background session, 
    // or NSURLSessionDownloadDelegate and NSURLSessionDelegate methods will not be called
    // as no delegate is attached to the session. See backgroundURLSession above.
    NSURLSession *backgroundSession = [self backgroundURLSession];

    NSLog(@"Rejoining session with identifier %@ %@", identifier, backgroundSession);

    // Store the completion handler to update your UI after processing session events
    [self addCompletionHandler:completionHandler forSession:identifier];
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
    NSLog(@"Background URL session %@ finished events.\n", session);

    if (session.configuration.identifier) {
        // Call the handler we stored in -application:handleEventsForBackgroundURLSession:
        [self callCompletionHandlerForSession:session.configuration.identifier];
    }
}

- (void)addCompletionHandler:(CompletionHandlerType)handler forSession:(NSString *)identifier
{
    if ([self.completionHandlerDictionary objectForKey:identifier]) {
        NSLog(@"Error: Got multiple handlers for a single session identifier.  This should not happen.\n");
    }

    [self.completionHandlerDictionary setObject:handler forKey:identifier];
}

- (void)callCompletionHandlerForSession: (NSString *)identifier
{
    CompletionHandlerType handler = [self.completionHandlerDictionary objectForKey: identifier];

    if (handler) {
        [self.completionHandlerDictionary removeObjectForKey: identifier];
        NSLog(@"Calling completion handler for session %@", identifier);

        handler();
    }
}

相关文章

  • 远程推送和后台数据获取

    详情:https://www.objc.io/issues/5-ios7/multitasking/ Backgr...

  • iOS手把手教你生成推送证书(测试和生产)

    本篇文章主要介绍的是那些需要集成远程推送的证书流程和注意事项 1.远程推送 远程推送指用户在App退到后台运行的时...

  • iOS极光推送生成推送证书的生产证书(一)

    本篇文章主要介绍的是那些需要集成远程推送的证书流程和注意事项 1.远程推送 远程推送指用户在App退到后台运行的时...

  • flutter 远程推送

    iOS 如果要在后台的时候收到远程推送,需要设置background modes 如果要处理后台收到的推送,推送消...

  • iOS10 推送通知 UserNotifications

    简介 新框架 获取权限 获取用户设置 注册APNS,获取deviceToken 本地推送流程 远程推送流程 通知策...

  • 读《高性能iOS应用开发》后记录

    1,静默远程推送、后台拉取可以后台更新数据,让应用在启动时直接加载更新过的数据,用的好将很大程度提升用户的感知体验...

  • push

    基础 将本地仓库中的数据推送到远程仓库中。 推送数据之前,应该先更新远程库中的数据。 git push <远程主机...

  • iOS 远程推送关闭开启功能

    开启远程推送 关闭远程推送 获取tableView(collection)中某一个cell相对于屏幕的frame

  • 融云即时通 :消息推送篇

    RongIM 消息推送 分为二类:1.远程推送:指 程序在后台 2分钟后被杀死,通过远程推送方式,实现消息通知2....

  • JPush推送

    移动端获取jPush推送消息,并点击进入详情,首先要设置别名和标签、获取设备id绑定到后台,才可以接收推送消息。具...

网友评论

      本文标题:远程推送和后台数据获取

      本文链接:https://www.haomeiwen.com/subject/zlicsftx.html