我是ios的新手,我想制作一个应用程序,在应用程序中,我必须在后台调用Web服务,
后台代码正常工作,但是当我尝试调用Web服务时,请不要转到“ connectionDidFinishLoading”功能
我在哪里做错了,请帮助我
这是我的代码
1.这是我的后台功能,每30秒调用一次Web服务

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
        if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
            UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

            __block UIBackgroundTaskIdentifier background_task; //Create a task object

            background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid


            }];



            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //Perform your tasks that your application requires

                while(TRUE)
                {
                    //backgroundTimeRemaining time does not go down.

                    //  NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
                    [UIApplication sharedApplication].applicationIconBadgeNumber++;
                    NSLog(@"\n\nRunning in the background!\n\n");

                    [self CallWebservices2];

                    [NSThread sleepForTimeInterval:30]; //wait for 1 sec
                }

                [application endBackgroundTask: background_task];
                background_task = UIBackgroundTaskInvalid;
                });
        }
    }}


2.这是我的呼叫webservices,此代码到达了CallWebservices2函数,但无法调用connectionDidFinishLoading

-(void)CallWebservices2
{

    NSString *urlString = [NSString stringWithFormat:@"http://yournurses.com/process/push.php?action=select_jobs&id=241"];

    NSLog(@"String Url = %@",urlString);

    NSURL *url = [NSURL URLWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    NSURLConnection *connnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

    [connnection start];


}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"Error==%@",error);





}





-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    [nsUrlResponseDataNurse setLength:0];

}



-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [nsUrlResponseDataNurse appendData:data];

}



-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{



    if ([nsUrlResponseDataNurse length]==0)

    {}
    else{
        NSString *str = [[NSString alloc]initWithData:nsUrlResponseDataNurse encoding:NSUTF8StringEncoding];

        allDataNurse = [str JSONValue];

        NSLog(@"%@",allDataNurse);

    }


}


在这里我在委托文件中定义

@property(nonatomic,retain)NSMutableData *nsUrlResponseDataNurse;
@property(nonatomic, retain) NSMutableArray *allDataNurse;


问候,
西恩·钱德瓦尼(Nishant Chandwani)

最佳答案

NSURLConnection支持“开箱即用”的异步网络事务。您不应从后台运行NSURLConnection。这是毫无意义和浪费的。该类旨在有效处理后台下载。

您在主线程上创建一个NSURLConnection并开始运行。它在后台完成工作,然后在主线程上调用您的委托方法。

如果仅在下载/ PUT完成时需要通知,则可以使用NSURLConnection类方法sendAsynchronousRequest:queue:completionHandler:来运行整个请求,然后在完成后调用完成处理程序。通常,您有在主队列上调用该方法的完成处理程序,因为一旦URL请求完成,该代码就会被调用。

您的代码可能如下所示:

  NSURL *url = [NSURL URLWithString: @"http://www.foo.php"];
  NSURLRequest *request = [NSURLRequest requestWithURL: url];
  [NSURLConnection sendAsynchronousRequest: request
                                     queue: [NSOperationQueue mainQueue]
                         completionHandler: ^(NSURLResponse *response,
                                              NSData *data,
                                              NSError *connectionError)
   {
     if (data.length > 0 && connectionError == nil)
     {
        //The data for the response is in "data" Do whatever is required
     }
   }
   ];


该代码将在后台运行请求,并在完成时调用完成代码中的代码。简单无痛。

关于ios - NSURLConnection,Web Service在后台ios中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23496330/

10-12 14:39
查看更多