我刚开始学iOS开发,正在开发一个需要在后台线程中运行任务从服务器获取数据的应用程序,因为我不想在主线程中锁定用户界面。这个任务将需要很长时间,我尝试使用NSTimer,但它仍然会锁定UI。我的任务是检查聊天界面中的新消息,我需要每5秒调用一次此任务。如果我使用NSTimer,当输入文本时,文本似乎会在执行此任务时停滞一会儿。有没有办法在不锁定UI的情况下处理此任务?请给我一些建议。非常感谢。
== 更新代码 ==
- (void)performBackgroundTask
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do background work
if([[NSUserDefaults standardUserDefaults] boolForKey:@"LoggedIn"]) {
NSDictionary * userDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"SessionDictionary"];
NSString *authenKey= [userDictionary valueForKey:@"authToken"];
NSString* limit = @"1000";
[[LSDataManager sharedDataManager] getLatestMessagesWithAuthKey:authenKey andLimit:limit withBlock:^ (NSDictionary* responseDict)
{
if (responseDict) {
[self loadDataFromServer:responseDict];
NSArray* lastMessageArray= nil;
//filter message data
if (self.MessagesArray.count >0) {
if (!self.isSeller) {
lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.receiverID withBuyerID:self.senderID];
}
else
{
lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.senderID withBuyerID:self.receiverID];
}
NSLog(@"filter array %@",lastMessageArray);
if([lastMessageArray count] >0){
//[self loadMessages:lastMessageArray];
if (self.TempdataSource == nil) {
self.TempdataSource = [NSMutableArray array];
}
else
{
[self.TempdataSource removeAllObjects];
}
self.TempdataSource = [[[ContentManager sharedManager] generateConversation:lastMessageArray withSenderID:self.senderID] mutableCopy];
}
}
}
}];
}
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI
//compare 2 arrays
if ([self.TempdataSource count] == [self.dataSource count]) {
NSLog(@"both are same");
}
else{
NSLog(@"both are different");
self.dataSource = [self.TempdataSource mutableCopy];
[self refreshMessages];
}
});
});
}