【问题标题】:How to get Web service response in an iOS app when application is in Background?当应用程序处于后台时,如何在 iOS 应用程序中获取 Web 服务响应?
【发布时间】:2014-06-26 10:15:18
【问题描述】:

我正在开发一个 iOS 应用程序,我在其中使用 NSURLConnection 的 Restful Web 服务,当我调用 Web 服务并在调用 Web 服务后按下主页按钮然后应用程序进入后台并且它在后台没有得到响应.在我的应用程序中,即使应用程序处于后台状态,也应该得到响应。

所以请给我建议任何合适的答案。

我应该使用NSURLSession 吗?

【问题讨论】:

标签: ios cocoa-touch background nsurlconnection nsurlsession


【解决方案1】:
NSURL *myURL = [NSURL URLWithString:@""]; // set your url here
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *getTask = [session downloadTaskWithURL:myURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // do stuff with the result
}];

// don't forget to start your task 
[getTask resume];

这里有一个不错的教程,您可能想学习: http://www.raywenderlich.com/51127/nsurlsession-tutorial

【讨论】:

    【解决方案2】:

    使用 UIBackgroundTaskIdentifier,类似这样的

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

      //启动后台服务,每10秒获取一次数据 [自我运行背景任务:10]; }

    • (void)runBackgroundTask: (int) 时间{

      UIApplication *app; app = [UIApplication sharedApplication]; //检查应用程序是否处于后台模式 if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {

      //create UIBackgroundTaskIdentifier and create tackground task, which starts after time
      __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
           [app endBackgroundTask:bgTask];
           bgTask = UIBackgroundTaskInvalid;
      }];
      
      dispatch_async(dispatch_get_main_queue(), ^{
          NSTimer *refreshTimer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(doRefresh) userInfo:nil repeats:YES];
          [[NSRunLoop currentRunLoop] addTimer:refreshTimer forMode:NSDefaultRunLoopMode];
      
          [app endBackgroundTask:bgTask];
          bgTask = UIBackgroundTaskInvalid;
      });
      

      } }

    doRefresh - 这是您提供网络服务的方法

    【讨论】:

    • 这不是正确的做法。请改用NSURLSession,它就是为此而生的。
    • @KPM 是的,我们可以使用 NSURLSession 但我认为 NSURLSession 仅在 iOS 7 中使用,对吗?
    • 您没有具体说明是否需要兼容 iOS 7 之前的版本。
    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    相关资源
    最近更新 更多