如果App甚至在ios中的BackGround状态下如何运行webServices?

时间:2017-01-05 06:18:36

标签: ios objective-c

您好我是Ios的新手,在我的应用中,我希望使用 BackGround Thread 运行我的Web服务,即使应用于Background State,我也希望运行此Web服务。

我该如何做这个场景?有谁可以帮助我吗?

我的代码如下。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self getServieCalling:@"MY URL"];
}

-(void)getServieCalling :(NSString*)mainurl{


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:mainurl,kServerBaseURL1]]

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:60.0];

    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error != nil) {

            NSString * BasicnetworkError = [error localizedDescription];
            NSString * AppendString = @"Http Response failed with the following ";
            NSString * networkError = [AppendString stringByAppendingString:BasicnetworkError];

            [self BasicError:networkError];

            return;
        }

        else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode != 200) {

                NSString *statusCodeError = [NSString stringWithFormat: @"Http Response failed with the following code %ld", (long)statusCode];



            }else{

                NSError *parseError;

                id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                NSLog(@"response object %@",responseObject);


                else {

                    NSLog(@"Error parsing JSON: %@", parseError);

                    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                    NSLog(@"responseString = %@", responseString);
                }
            }
        }

    }];

    [task resume];

   });
}

0 个答案:

没有答案