Kyl*_*e C 12 iphone nsurlconnection ios restkit ios5
我的应用需要在后台跟踪用户位置,但无法发送"获取"请求.当应用程序到达前台时,会立即发送http请求.我正在使用RestKit来处理所有网络请求,我按照本教程设置了我的后台位置服务.在我的applicationDidEnterBackground中
-(void)applicationDidEnterBackground:(UIApplication *)application
{
self.bgLocationManager = [[CLLocationManager alloc] init];
self.bgLocationManager.delegate = self;
[self.bgLocationManager startMonitoringSignificantLocationChanges];
NSLog(@"Entered Background");
}
Run Code Online (Sandbox Code Playgroud)
我在applicationDidBecomeActive委托中停止监视有意义的位置变化
这是我的locationManager委托,我接受新的更新位置并发送到我的服务器
-(void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"I am in the background");
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// ANY CODE WE PUT HERE IS OUR BACKGROUND TASK
NSString *currentLatitude = [[NSString alloc]
initWithFormat:@"%g",
newLocation.coordinate.latitude];
NSString *currentLongitude = [[NSString alloc]
initWithFormat:@"%g",
newLocation.coordinate.longitude];
NSString *webToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"userWebToken"];
NSLog(@"I am in the bgTask, my lat %@", currentLatitude);
NSDictionary *queryParams;
queryParams = [NSDictionary dictionaryWithObjectsAndKeys:webToken, @"auth_token", currentLongitude, @"lng", currentLatitude, @"lat", nil];
RKRequest* request = [[RKClient sharedClient] post:@"/api/locations/background_update" params:queryParams delegate:self];
//default is RKRequestBackgroundPolicyNone
request.backgroundPolicy = RKRequestBackgroundPolicyContinue;
// AFTER ALL THE UPDATES, close the task
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
Run Code Online (Sandbox Code Playgroud)
网络请求按计划运行,但不会在后台调用.我还需要其他步骤吗?在我的info.plist中,我有必需的背景模式键和位置服务作为值.
编辑
我也提到过去的答案.我通过在didUpdateToLocation调用中放置日志来运行一些测试并且它们都被调用但是没有发送'get'请求.相反,当我最终将应用程序启动到前台时,它会发送所有构建的网络请求(超过10个).
编辑(2)我在我的请求中添加了RKRequestBackgroundPolicyContinue,但它没有改变我的结果.(正如你可以看到这里在后台上传/下载restkit).我看到Restkit初始化主机但是在应用程序变为活动状态之前无法发送请求.
回答
RestKit必须做一些在后台禁止的事情.使用NSURLRequest非常有效.
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/api/locations/background_update"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
Run Code Online (Sandbox Code Playgroud)
可以使用同步请求,因为没有UI可以破坏后台任务
重新创建原始建议作为答案
\n\n\n\n您是否尝试过用库存同步 NSURLConnection 替换restKit 调用?\xe2\x80\x93 dklt 九月 20 日
\n
| 归档时间: |
|
| 查看次数: |
5073 次 |
| 最近记录: |