0

更新:这是我在 github 存储库中使用的所有文件。也许它比我的代码片段更有帮助:

appDelegate
mainViewController
calendarHandler

NSString* result = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err];

这就是我在项目中用来从网站获取数据的线路。我在 NSOperationQueue 中运行它,当我在前台运行我的应用程序时,它可以正常工作。但是,我也将我的应用程序设置为使用 performFetchWithCompletionHandler 在后台运行。我的所有设置代码都可以使用 performFetch 正常工作,但是当它到达我上面概述的行时,应用程序会挂起,直到我再次将我的应用程序带到前台。我怎样才能让它在后台工作?

在我的 AppDelegate 中,我有 performFetchWithCompletionHandler:

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{    
 UINavigationController *navigationController = (UINavigationController*) self.window.rootViewController;

id topViewController = navigationController.topViewController;

if ([topViewController isKindOfClass:[ViewController class]])
{
    [(ViewController*)topViewController autoLogin];
}

completionHandler(UIBackgroundFetchResultNewData);
}

我的 NSOperationQueue 在我的 MainViewController 中是这样构建的:

- (void) autologin
{
NSOperationQueue* backgroundQueue = [NSOperationQueue new];

ch = [[myEventHandler alloc] init];

NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithTarget:ch selector:@selector(runEvents:) object:login];

[backgroundQueue addOperation:operation];
}

在 MyEventHandler 我有 runEvents

 - (void) runEvents
{
     NSURL* urlRequest = [NSURL URLWithString:@"http://www.google.com"];

    NSError* err = nil;

    NSString* result = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err];
}
4

2 回答 2

0

have you tried using NSURLConnection (asynchronous) instead of stringWithContentsOfURL (synchronous)?

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
[NSURLConnection sendAsynchronousRequest:request queue: [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *theResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// blah blah
}];
于 2013-11-15T13:24:18.853 回答
0

试试这段代码:

 NSString *urlString=[NSString stringWithFormat:@"%@listcontact.php?uid=%@&page=0",LocalPath,appdel.strid];
NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
       NSError *error1;
     NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
 }];
于 2013-11-15T13:28:58.017 回答