iOS Periodically perform a low-priority task while the system is idle

时间秒杀一切 提交于 2019-12-24 07:48:34

问题


In the iOS App development process. I want to periodically perform a low priority task. And do not want this task will affect the main program of work. What is the way to achieve it?

Now I use the timer to perform periodical task, but often find the App is not smooth.

The low priority task sometime need run on the main thread, such as check pasteboard than display the content on UI.


回答1:


You will have to use Blocks(Completion handlers) for this, it's part of GCD. This will stay away from main thread.

Make a NSObject class named "backgroundClass".

in .h file

typedef void (^myBlock)(bool success, NSDictionary *dict);

@interface backgroundClass : NSObject

@property (nonatomic, strong)  myBlock completionHandler;

-(void)taskDo:(NSString *)userData block:(myBlock)compblock;

in .m file

-(void)taskDo:(NSString *)userData block:(myBlock)compblock{
  // your task here
// it will be performed in background, wont hang your UI. 
// once the task is done call "compBlock" 

compblock(True,@{@"":@""});
}

in your viewcontroller .m class

- (void)viewDidLoad {
    [super viewDidLoad];
backgroundClass *bgCall=[backgroundClass new];

 [bgCall taskDo:@"" block:^(bool success, NSDictionary *dict){
// this will be called after task done. it'll pass Dict and Success.    

dispatch_async(dispatch_get_main_queue(), ^{
 // write code here if you need to access main thread and change the UI.
// this will freeze your app a bit.
});

}];
}


来源:https://stackoverflow.com/questions/47066887/ios-periodically-perform-a-low-priority-task-while-the-system-is-idle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!