后台远程可操作通知Web服务调用不起作用?

时间:2016-06-30 13:34:18

标签: ios objective-c push-notification

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    //call 2 web service here.
    [self jsonParser:jsonData];
    completionHandler(UIBackgroundFetchResultNewData);
}

我将此方法称为如下

-(void)jsonParser:(NSData *)data
{  
    //[downloader downloadXMLContentsFromURL:actualURL withXML:encrypted];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:actualURL]
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:HTTP_REQUEST_TIME_OUT];
    [request setHTTPMethod:@"POST"];

    NSString *encodedXML = [encrypted urlEncodeUsingEncoding:NSUTF8StringEncoding];
    NSString *params = [NSString stringWithFormat:@"%@=%@", REQUEST_PARAMETER_NAME, encodedXML];
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    {
         NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:nil];
    }];
    [postDataTask resume];
    //Here call to other service not shown
}

我已经从“远程通知”

功能启用了“后台获取”功能

我是否需要实施此方法?

- (void)application:(UIApplication *)application performFetchWithCompletionHandler: (void (^)(UIBackgroundFetchResult))completionHandler 

当应用处于活动状态时,此功能正常。但不适用于App是在Background和Closed.same时,当我打开应用程序它工作正常。我想在应用程序关闭时在后台运行服务。怎么解决这个问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您必须启用后台提取服务,如下所示,您需要设置MinimumBackgroundFetchInterval。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [application setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum];
    return YES;
}

并实现类似于此公共方法实现的方法

-(void)jsonParser:(NSData *)data Completion: (void (^)(UIBackgroundFetchResult))completionHandler
{
    //[downloader downloadXMLContentsFromURL:actualURL withXML:encrypted];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:actualURL]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:HTTP_REQUEST_TIME_OUT];
    [request setHTTPMethod:@"POST"];

    NSString *encodedXML = [encrypted urlEncodeUsingEncoding:NSUTF8StringEncoding];
    NSString *params = [NSString stringWithFormat:@"%@=%@", REQUEST_PARAMETER_NAME, encodedXML];
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
    {
        NSError *localError = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:&localError];
        if (localError != nil) {
            // handle your data here
            completionHandler(UIBackgroundFetchResultNewData);
            NSLog(@"New data was fetched.");
        }else{
            completionHandler(UIBackgroundFetchResultFailed);
            NSLog(@"Failed to fetch new data.");
        }
    }];
    [postDataTask resume];
    //Here call to other service not shown
}

和像这样的实现方法

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSDate *fetchStart = [NSDate date];

    [self jsonParser:jsonData Completion:^(UIBackgroundFetchResult result){

        NSDate *fetchEnd = [NSDate date];
        NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
        NSLog(@"Background Fetch Duration: %f seconds", timeElapsed);
    }];
}

我希望这会对您有所帮助,请查看此链接http://www.appcoda.com/ios7-background-fetch-programming/