stringWithContentsOfUrl在后台

时间:2013-11-14 02:42:32

标签: ios

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

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];
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用NSURLConnection(异步)而不是stringWithContentsOfURL(同步)?

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
}];

答案 1 :(得分: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];
 }];