2016-06-30 2 views
0
- (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 
} 

Я включил «Фон Fetch» ​​от возможностей и «Remote Notification»

я должен реализовать этот метод делать?

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

Это нормально работает, когда приложение активно. Но не работает для приложения в фоновом режиме и закрыто. Когда я открываю приложение, он отлично работает. Я хочу запустить службу в фоновом режиме, когда приложение закрывается. как это исправить? любая помощь будет оценена.

ответ

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/

+0

Работал как шарм. Спасибо за ответ. –

Смежные вопросы