我需要为我的iOS应用程序执行一个非常简单的背景调查。它只需要对我的web服务器进行一次调用,并根据我的应用程序中的某些内容检查它检索的号码。有可能做这样的背景调查吗?如果是这样,我可以做些什么来把它们组合在一起呢?
编辑
为了澄清我所说的背景:我指的是电话中的背景。当应用程序不存在时。可以在后台执行此请求吗?显然,这个应用程序并没有完全退出多任务处理。
发布于 2013-09-13 07:01:12
这听起来像是NSOperationQueue的完美选择。
http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
您可以编写一个操作,然后在需要时将其放入队列中。
或者,更简单的是,你可以只做一个非常简单的异步调用。
+ (NSArray *) myGetRequest: (NSURL *) url{
NSArray *json = [[NSArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:
url];
NSError *error;
if (data)
json = [[NSArray alloc] initWithArray:[NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error]];
if (error)
NSLog(@"%@", error)
return json;
}然后把它放在一个简单的调度块中..。
dispatch_queue_t downloadQueueA = dispatch_queue_create("updater", NULL);
dispatch_async(downloadQueueA, ^{
// stuff done here will happen in the background
NSArray * arrayOfData = [self myGetRequest: myURL];
// could be array... dictionary... whatever, you control this by returning the type of data model you want from the server formatted as JSON data
NSString * stringValue = arrayOfData[index];
dispatch_async(dispatch_get_main_queue(), ^{
// perform checking here and do whatever updating you need to do based on the data
});
});发布于 2013-09-13 07:10:55
有许多方法可以检查服务器和检索数据。
以下是我的建议:
>G211
如果你的服务器速度很快,你只需要获取一个数字,你可以在主界面中完成,否则使用:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// your request here
});按照要求以不同的方式工作。
请记住检查互联网连接和您的服务器是否可用,并使用NSURLRequest委派来管理连接错误
发布于 2013-09-13 06:57:02
https://stackoverflow.com/questions/18775257
复制相似问题