I use firebase in swift, I call the listener in viewDidAppear: and as it is written in the docs it should't download the same data again but now every time the view appears the same data will be displayed.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
getData()
self.messagesRef.keepSynced(true)
}
func getData(){
messagesRef.observeEventType(.ChildAdded) { (mesData: FDataSnapshot!) -> Void in
let messageDict = mesData.value as! NSDictionary
let key = mesData.key
self.likedRef = self.ref.childByAppendingPath("likedMessages/\(currentUser.uid)/\(key)")
self.likedRef.observeSingleEventOfType(.Value) { (likedFd: FDataSnapshot!) -> Void in
if likedFd.value is NSNull{
let liked = false
let message = Message(message: messageDict, key: key, liked: liked, topicKey: self.topic.key)
self.messages.append(message)
self.messages.sortInPlace{$0.createdAt.compare($1.createdAt) == .OrderedDescending}
}
else{
let liked = likedFd.value as! Bool
let message = Message(message: messageDict, key: key, liked: liked, topicKey: self.topic.key)
self.messages.append(message)
self.messages.sortInPlace{$0.createdAt.compare($1.createdAt) == .OrderedDescending}
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.messagesTableView.reloadData()
}
self.likedRef.keepSynced(true)
}
print(mesData.value)
}
}
If you add the first listener to a location, Firebase will download the current data for that location and start synchronizing the changes. It will keep a copy of the data available in memory.
If you add a second listener to the location, while the first one is still active, Firebase will not re-download the data. I just quickly verified this http://jsbin.com/foduxun/edit?js,console.
If you remove the first listener before you attach the second listener, Firebase will purge its cache. So then when you attach a listener again, it will re-download the data.
If you want to keep the data available on the device even after you detached all listeners, enable disk persistence:
[Firebase defaultConfig].persistenceEnabled = YES;
Related
In my application I use Firebase Realtime Database to store data about users. I would like to be sure that when I read this data to display it in the view (e.g. their nickname), that the reading has been done before displaying it. Let me explain:
//Initialization of user properties
static func initUsers(){
let usersref = dbRef.child("Users").child(userId!)
usersref.observeSingleEvent(of: .value) { (DataSnapshot) in
if let infos = DataSnapshot.value as? [String : Any]{
self.username = infos["username"] as! Int
//The VC is notified that the data has been recovered
let name = Notification.Name(rawValue: "dataRetrieved")
let notification = Notification(name: name)
NotificationCenter.default.post(notification)
}
}
}
This is the code that runs in the model and reads the user's data when they log in.
var isFirstAppearance = true
override func viewDidLoad() {
super.viewDidLoad()
//We initialise the properties associated with the user
Users.initUsers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isFirstAppearance {
let name = Notification.Name(rawValue: "dataRetrieved")
NotificationCenter.default.addObserver(self, selector: #selector(registerDataToView), name: name, object: nil)
isFirstAppearance = false
}
else{
registerDataToView()
}
}
//The user's data is assigned to the view
#objc func registerDataToView(){
usernameLabel.text = String(Users.username)
}
Here we are in the VC and when the view loads we call initUsers in viewDidLoad. In viewWillAppear, if it's the first time we load the view then we create a listener which calls registerDataToView if the reading in the database is finished. Otherwise we simply call registerDataToView (this is to update the labels when we return to this VC).
I would like to know if it is possible, for example when we have a very bad connection, that the listener does not intercept the dataRetrieved notification and therefore that my UI displays only the default texts? Or does the headset wait to receive the notification before moving on?
If it doesn't wait then how can I wait for the database read to finish before initializing the labels?
Thanks for your time :)
Don't wait. Never wait. Tell the receiver that the data are available with a completion handler
static func initUsers(completion: #escaping (Bool) -> Void) {
let usersref = dbRef.child("Users").child(userId!)
usersref.observeSingleEvent(of: .value) { (DataSnapshot) in
if let infos = DataSnapshot.value as? [String : Any]{
self.username = infos["username"] as! Int
completion(true)
return
}
completion(false)
}
}
And use it
override func viewDidLoad() {
super.viewDidLoad()
//We initialise the properties associated with the user
Users.initUsers { [unowned self] result in
if result (
// user is available
} else {
// user is not available
}
}
}
I'm trying to implement a contacts reader in Xamarin.iOS which tries to iterate over the iOS contacts in all CNContactStore containers. Instead of loading all contacts into memory, I need to iterate over a contacts resultset batch by batch (paging contacts). However all the examples that I saw in SO load almost all contacts into memory first.
i.e. This question has loads of similar examples that read all contacts at once. Although these examples have logic which iterates one by one, it is not evident to me how to skip N and take the next N number of contacts without iterating from the beginning on the next call (which looks sub optimal at least to me).
Apple's own documentation reads
When fetching all contacts and caching the results, first fetch all contacts identifiers, then fetch batches of detailed contacts by identifiers as required
I was able to do this easily for Android using the cursor based approach available in its SDK. Is this at all possible for iOS? If not how can we handle a large number of contacts (e.g. something above 2000, etc.). I don't mind examples in swift. I should be able to convert them to Xamarin.
Thanks in advance.
Here's the approach I took, granted my requirements did not allow persisting contacts, only holding in active memory. Not saying it's the right approach, but fetching all identifiers first, then lazily fetching all keys for a specific contact as needed, did improve performance. It also avoids performing a lookup when the contact doesn't exist.
I also tried using NSCache instead of dictionary, but ran into issue when I needed to iterate over the cache.
I truncated functions that aren't relevant to the topic but hopefully still convey the approach.
import Contacts
extension CNContactStore {
// Used to seed a Contact Cache with all identifiers
func getAllIdentifiers() -> [String: CNContact]{
// keys to fetch from store
let minimumKeys: [CNKeyDescriptor] = [
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactIdentifierKey as CNKeyDescriptor
]
// contact request
let request = CNContactFetchRequest(keysToFetch: minimumKeys)
// dictionary to hold results, phone number as key
var results: [String: CNContact] = [:]
do {
try enumerateContacts(with: request) { contact, stop in
for phone in contact.phoneNumbers {
let phoneNumberString = phone.value.stringValue
results[phoneNumberString] = contact
}
}
} catch let enumerateError {
print(enumerateError.localizedDescription)
}
return results
}
// retreive a contact using an identifier
// fetch keys lists any CNContact Keys you need
func get(withIdentifier identifier: String, keysToFetch: [CNKeyDescriptor]) -> CNContact? {
var result: CNContact?
do {
result = try unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch)
} catch {
print(error)
}
return result
}
}
final class ContactsCache {
static let shared = ContactsCache()
private var cache : [String : ContactCacheItem] = [:]
init() {
self.initializeCache() // calls CNContactStore().getAllIdentifiers() and loads into cache
NotificationCenter.default.addObserver(self, selector: #selector(contactsAppUpdated), name: .CNContactStoreDidChange, object: nil)
}
private func initializeCache() {
DispatchQueue.global(qos: .background).async {
let seed = CNContactStore.getAllIdentifiers()
for (number, contact) in seed{
let item = ContactCacheItem.init(contact: contact, phoneNumber: number )
self.cache[number] = item
}
}
}
// if the contact is in cache, return immediately, else fetch and execute completion when finished. This is bit wonky to both return value and execute completion, but goal was to reduce visible cell async update as much as possible
public func contact(for phoneNumber: String, completion: #escaping (CNContact?) -> Void) -> CNContact?{
if !initialized { // the cache has not finished seeding, queue request
queueRequest(phoneNumber: phoneNumber, completion: completion) // save request to be executed as soon as seeding completes
return nil
}
// item is in cache
if let existingItem = getCachedContact(for: phoneNumber) {
// is it being looked up
if existingItem.lookupInProgress(){
existingItem.addCompletion(completion: completion)
}
// is it stale or has it never been looked up
else if existingItem.shouldPerformLookup(){
existingItem.addCompletion(completion: completion)
refreshCacheItem( existingItem )
}
// its current, return it
return existingItem.contact
}
// item is not in cache
completion(nil)
return nil
}
private func getCachedContact(for number: String) -> ContactCacheItem? {
return self.cache.first(where: { (key, _) in key.contains( number) })?.value
}
// during the async initialize/seeding of the cache, requests may come in from app, so they are temporarily 'queued'
private func queueRequest(phoneNumber: String, completion: #escaping (CNContact?) -> Void){..}
// upon async initialize/seeding completion, queued requests can be executed
private func executeQueuedRequests() {..}
// if app receives notification of update to user contacts, refresh cache
#objc func contactsAppUpdated(_ notification: Notification) {..}
// if a contact has gone stale or never been fetched, perform the fetch
private func refreshCacheItem(_ item: ContactCacheItem){..}
// if app receives memory warning, dump data
func clearCaches() {..}
}
class ContactCacheItem : NSObject {
var contact: CNContact? = nil
var lookupAttempted : Date? // used to determine when last lookup started
var lookupCompleted : Date? // used to determien when last successful looup completed
var phoneNumber: String //the number used to look this item up
private var callBacks = ContactLookupCompletion() //used to keep completion blocks for lookups in progress, in case multilpe callers want the same contact info
init(contact: CNContact?, phoneNumber: String){..}
func updateContact(contact: CNContact?){..} // when a contact is fetched from store, update it here
func lookupInProgress() -> Bool {..}
func shouldPerformLookup() -> Bool {..}
func hasCallBacks() -> Bool {..}
func addCompletion(completion: #escaping (CNContact?) -> Void){..}
}
I'm working on an application which uses a shared Core Data database between itself and a Notification Service Extension. Both the application and the extension are able to read and write to the same Core Data database.
The application however needs to update the displayed information as soon as the corresponding fields change in the database. Is there an efficient way for it to be notified of the changes the extension makes to the database? I assume the application and the extension use different managed contexts to access the database. Or am I wrong?
Using SwiftEventBus this is pretty straight forward
Controller.swift
let yourObj = YourObject()
SwiftEventBus.post("EventName", sender: yourObj)
Extension.swift
let yourObj = YourObject()
SwiftEventBus.post("EventName", sender: yourObj)
AppDelegate.swift
SwiftEventBus.onMainThread(self, name: "EventName") { (result) in
if let yourObject = result.object as? YourObject {
// Queue or write the data as per your need
}
}
I found a solution to the problem I described after being pointed towards using notification by #CerlinBoss. It is possible to send a notification from the extension to the application (or vice versa). This can be done in iOS using a Darwin notification center. The limitation however is that you can't use the notification to send custom data to your application.
After reading many articles I decided that I'd avoid making changes to the Core Data database from two different processes and using multiple managed contexts. Instead, I queue the data I need to communicate to the application inside a key in the UserDefaults and once the application is notified of the changes, I'd dequeue them and update the Core Data context.
Common Code
Swift 4.1
import os
import Foundation
open class UserDefaultsManager {
// MARK: - Properties
static let applicationGroupName = "group.com.organization.Application"
// MARK: - Alert Queue Functions
public static func queue(notification: [AnyHashable : Any]) {
guard let userDefaults = UserDefaults(suiteName: applicationGroupName) else {
return
}
// Retrieve the already queued notifications.
var alerts = [[AnyHashable : Any]]()
if let data = userDefaults.data(forKey: "Notifications"),
let items = NSKeyedUnarchiver.unarchiveObject(with: data) as? [[AnyHashable : Any]] {
alerts.append(contentsOf: items)
}
// Add the new notification to the queue.
alerts.append(notification)
// Re-archive the new queue.
let data = NSKeyedArchiver.archivedData(withRootObject: alerts)
userDefaults.set(data, forKey: "Notifications")
}
public static func dequeue() -> [[AnyHashable : Any]] {
var notifications = [[AnyHashable : Any]]()
// Retrieve the queued notifications.
if let userDefaults = UserDefaults(suiteName: applicationGroupName),
let data = userDefaults.data(forKey: "Notifications"),
let items = NSKeyedUnarchiver.unarchiveObject(with: data) as? [[AnyHashable : Any]] {
notifications.append(contentsOf: items)
// Remove the dequeued notifications from the archive.
userDefaults.removeObject(forKey: "Notifications")
}
return notifications
}
}
Extension:
Swift 4.1
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
os_log("New notification received! [%{public}#]", bestAttemptContent.body)
// Modify the notification content here...
// Queue the notification and notify the application to process it
UserDefaultsManager.queue(notification: bestAttemptContent.userInfo)
notifyApplication()
contentHandler(bestAttemptContent)
}
}
func notifyApplication() {
let name: CFNotificationName = CFNotificationName.init("mutableNotificationReceived" as CFString)
if let center = CFNotificationCenterGetDarwinNotifyCenter() {
CFNotificationCenterPostNotification(center, name, nil, nil, true)
os_log("Application notified!")
}
}
Application:
Swift 4.1
// Subscribe to the mutableNotificationReceived notifications from the extension.
if let center = CFNotificationCenterGetDarwinNotifyCenter() {
let name = "mutableNotificationReceived" as CFString
let suspensionBehavior = CFNotificationSuspensionBehavior.deliverImmediately
CFNotificationCenterAddObserver(center, nil, mutableNotificationReceivedCallback, name, nil, suspensionBehavior)
}
let mutableNotificationReceivedCallback: CFNotificationCallback = { center, observer, name, object, userInfo in
let notifications = UserDefaultsManager.dequeue()
for notification in notifications {
// Update your Core Data contexts from here...
}
print("Processed \(notifications.count) dequeued notifications.")
}
I am building an app that populates data in a collectionView. The data come from API calls. When the screen first loads I get the products and store them locally in my ViewController.
My question is when should I get the products again and how to handle screen changing. My data will change when the app is running (sensitive attributes like prices) , but I don't find ideal solution to make the API call each time viewWillAppear is being called.
Can anybody please tell me what is the best pattern to handle this situation. My first though was to check if [CustomObject].isEmpty on viewWillAppear and then make the call. Including a timer that check again every 10-15 minutes for example.
Thank you for your input.
I'm not sure what the data looks like and how your API in detail works, but you certainly don't have to call viewWillAppear when your API updates the data.
There are two possible solutions to be notified when your data is updated.
You can either use a notification that lets you know whether the API is providing some data. After the Data has been provided your notification then calls to update the collection view. You can also include in the objects or structs that contain the data from your API the "didSet" call. Every time the object or struct is being updated the didSet routine is called to update your collection view.
To update your collection view you simply call the method reloadData() and the collection view will update itself and query the data source that now contains the newly received data from your API.
Hope this helps.
There is no set pattern but it is advisable not to send repeated network requests to increase energy efficiency (link). You can check the time interval in ViewWillApear and send the network requests after certain gap or can use timer to send requests at time intervals. First method would be better as it sends request only when user is on that screen. You can try following code snippet to get the idea
class ViewController: UIViewController {
let time = "startTime"
let collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
update()
}
private func update() {
if let startDateTime = NSUserDefaults.standardUserDefaults().objectForKey(time) as? NSDate {
let interval = NSDate().timeIntervalSinceDate(startDateTime)
let elapsedTime = Int(interval)
if elapsedTime >= 3600 {
makeNetworkRequest()
NSUserDefaults.standardUserDefaults().setObject(startDateTime, forKey: time)
}
} else {
makeNetworkRequest()
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: time)
}
}
func makeNetworkRequest() {
//Network Request to fetch data and update collectionView
let urlPath = "http://MyServer.com/api/data.json"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
return
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] else {
print("Error in json parsing")
return
}
self.collectionView.reloadData()
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
I'm trying to understand CloudKit, but I'm having an issue figuring out a real-world issue if I eventually turned it into an app.
I've got a tableviewcontroller that's populated by CloudKit, which works fine. I've got a detailviewcontroller that is pushed when you tap one of the entries in the tableview controller. The detailviewcontroller pulls additional data from CloudKit that wasn't in the initial tableviewcontroller. All of this works perfectly fine.
Now, the detailviewcontroller allows changing of an image and saving it back to a public database. That's working fine as well.
The scenario I'm dealing with is thinking about this core function being used in an app by multiple people. If one person uploads a photo (overwriting an existing photo for one of the records), what happens if another user currently has the app in the background? If they open the app, they'll see the last photo they saw on that page, and not the new photo. So I want to reload the data from CloudKit when the app comes back to the foreground, but I must be doing something wrong, because it's not working. Using the simulator and my actual phone, I can change a photo on one device and the other device (simulator or phone) doesn't update the data when it comes into the foreground.
Here's the code I'm using: First in ViewController.swift:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println("viewDidLoad")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "activeAgain", name: UIApplicationWillEnterForegroundNotification, object: nil)
and then the activeAgain function:
func activeAgain() {
println("Active again")
fetchItems()
self.tblItems.reloadData()
println("Table reloaded")
}
and then the fetchItems function:
func fetchItems() {
let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Items", predicate: predicate)
publicDatabase.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
if error != nil {
println(error)
}
else {
println(results)
for result in results {
self.items.append(result as! CKRecord)
}
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.tblItems.reloadData()
self.tblItems.hidden = false
})
}
}
}
I tried adding a reload function to viewWillAppear, but that didn't really help:
override func viewWillAppear(animated: Bool) {
tblItems.reloadData()
}
Now here's the code in DetailViewController.swift:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "activeAgain", name: UIApplicationWillEnterForegroundNotification, object: nil)
self.imageScrollView.contentSize = CGSizeMake(1000, 1000)
self.imageScrollView.frame = CGRectMake(0, 0, 1000, 1000)
self.imageScrollView.minimumZoomScale = 1.0
self.pinBoardScrollView.maximumZoomScale = 8.0
showImage()
and then the showImage function:
func showImage() {
imageView.hidden = true
btnRemoveImage.hidden = true
viewWait.hidden = true
if let editedImage = editedImageRecord {
if let imageAsset: CKAsset = editedImage.valueForKey("image") as? CKAsset {
imageView.image = UIImage(contentsOfFile: imageAsset.fileURL.path!)
imageURL = imageAsset.fileURL
self.title = "Image"
imageView.hidden = false
btnRemoveImage.hidden = false
btnSelectPhoto.hidden = true
}
}
}
and the activeAgain function:
func activeAgain() {
showImage()
println("Active again")
}
Neither of these ViewControllers reload the data from CloudKit when they return. It's like it's cached the table data for the first ViewController and the image for the DetailViewController and it's using that instead of downloading the actual CloudKit data. I'm stumped, so I figure I better try this forum (my first post!). Hopefully I included enough required info to be useful.
Your showImage function is using a editedImage CKRecord. Did you also reload that record? Otherwise the Image field in that record would then still contain the old CKAsset.
Besides just reloading on a moment you feel right, you could also let the changes be pushed by creating a CloudKit subscription. Then your data will even change when it's active and changed by someone else.