如何在我的iPad应用程序中应用背景进程而不影响前台运行的进程?
问题描述:
我正在开发一个iPad应用程序,我需要从Web服务下载文件,我不希望它影响在前台运行的任何其他进程。如何在我的iPad应用程序中应用背景进程而不影响前台运行的进程?
我在本地应用程序中显示来自本地数据库的数据,而且这些数据来自Web服务。
帮助被赞赏。
非常感谢您提前。
答
一些想法:
可以运行在单独的线程下载过程。
写类,如下
@interface FileDownloader:的NSOperation
//使用以下方法:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:fileRecord.fileURLString]] delegate:self startImmediately:YES];
答
NSURLConnection的及其委托方法将允许一个URL请求的异步(后台线程)加载。
请参考NSURLConnection Class Reference
从你应该分析它的另一个辅助线程服务器获取数据后。然后你可以将它保存到数据库。
您可以在Apple示例应用程序中找到更好的演示。请检查TopPaid app。
此示例应用程序没有数据库管理模块。但会教你开发一个通用(iPad和iPhone兼容的应用程序)。
答
您可以使用下面的方法线程使用脱离线程
[NSThread detachNewThreadSelector:@selector(yourMethod) toTarget:self withObject:nil];
现在在方法执行你的任务
-(void) yourMethod {
//ur work
}
好运
答
当从服务在后台下载,我更喜欢使用在单独线程上运行的同步调用。这是我在大多数应用程序中的做法。
打电话给我的那个旋转单中的一个新的线程
[[MyServiceSingleton sharedInstance] doSomeWorkInBackground:param1];
通用的方法 - 定义私有方法 - doSomeWorkBackgroundJob(我用的是空类中的方法)背景中doSomeWorkInBackground方法
[self performSelectorInBackground:@selector(doSomeWorkBackgroundJob:) withObject:param1];
内调用工作 - 创建池,做工,排水池
- (void)doSomeWorkBackgroundJob:(NSString *)param1 {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
assert(pool != nil);
// you can call another method here or just create your synchronous request and handle the response data
[pool drain];
}
谢谢你,我确实使用这种方法来调用下载类(连接方法) – NIKHIL 2011-03-18 14:51:46