Avijit Nagare Avijit Nagare - 5 months ago 18
Objective-C Question

Background remote actionable notification web service call not working?

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


I called this method as follows

-(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
}


I have enabled "Background Fetch" from capabilities also "Remote Notification"

Do i need to implement this Method?

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


This works fine when app is active. But not working for App is in Background and Closed.same time when i open app it works fine.I want to run service in background when app close. how to fix this ? any help will appreciated.

Answer

you have to enable background fetch service and as following you need to set MinimumBackgroundFetchInterval

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.

        [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

        return YES;
    }

and Implement the method like this Public method implementation

-(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
}

and Implement method like this

-(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);

    }];


}

I hope this will help you and please check this link http://www.appcoda.com/ios7-background-fetch-programming/