Token de notificação de região no encadeamento em segundo plano
Eu estava tentando buscar dados da região no segmento de segundo plano e adicionar um bloco de notificação (iOS, Swift).
Exemplo básico:
func initNotificationToken() {
DispatchQueue.global(qos: .background).async {
let realm = try! Realm()
results = self.getRealmResults()
notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
switch changes {
case .initial:
self?.initializeDataSource()
break
case .update(_, let deletions, let insertions, let modifications):
self?.updateDataSource(deletions: deletions, insertions: insertions, modifications: modifications)
break
case .error(let error):
fatalError("\(error)")
break
}
}
}
}
func initializeDataSource() {
// process the result set data
DispatchQueue.main.async(execute: { () -> Void in
// update UI
})
}
func updateDataSource(deletions: [Int], insertions: [Int], modifications: [Int]) {
// process the changes in the result set data
DispatchQueue.main.async(execute: { () -> Void in
// update UI
})
}
Ao fazer isso eu recebo
'Can only add notification blocks from within runloops'
Eu tenho que fazer um processamento mais extenso com os dados retornados e gostaria de voltar apenas ao thread principal ao atualizar a interface do usuário após o término do processamento.
Outra maneira provavelmente seria buscar novamente os dados após qualquer atualização no encadeamento em segundo plano e depois fazer o processamento, mas parece uma sobrecarga evitável.
Alguma sugestão sobre as melhores práticas para resolver isso?