I have an apple watch complication and the iPhone app running side by side. I have a button within the app to transmit application context dictionary to the watch. I expect to see the complication title to be refreshed.
I cannot seem to force the "tap button -> see update on the complication" kind of behavior.
What is the appropriate method to force a complication update? How can I refresh my apple watch complication instantly?
I do see the title changes, but I think it requires me to tap on the complication to open it's apple watch app first. How can I get the complication to update itself on the Watch home screen?
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: #escaping (CLKComplicationTimelineEntry?) -> Void) {
if complication.family == .graphicRectangular {
let template = CLKComplicationTemplateGraphicRectangularLargeImage()
//...configure
return template
}
}
I see this apple provided code that refreshes the complication. I'm not sure if it is too much, or if calling extendTimeline alone is sufficient if I'm generating the complication using the entry above.
func refreshComplication() {
#if os(watchOS)
let server = CLKComplicationServer.sharedInstance()
if let complications = server.activeComplications {
for complication in complications {
// Call this method sparingly. If your existing complication data is still valid,
// consider calling the extendTimeline(for:) method instead.
server.reloadTimeline(for: complication)
}
}
#endif
}
You should be able to do this by calling the refreshComplication() function from your didReceiveApplicationContext block in the file which has your WCSessionDelegate.
So if you are receiving the title via an applicationContext message your code would look something along these lines.
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
if let updatedTitle = applicationContext["updatedTitle"] {
if let title = updateTitle as? String {
//Remeber that complicationServer.swift is a seperate process therefore you will need to store the received data somehow.
UserDefaults.standard.set(title, forKey: "complicationTitle")
refreshComplication()
}
}
}
I have a setting in my iOS App that lets the user change their target and using this method refreshed the complication with the new target almost instantly. However, I believe once your complication has used up its cpu budget nothing will happen, but hopefully that is not happening for you. See https://developer.apple.com/documentation/clockkit/clkcomplicationserver/1627891-reloadtimeline
Hope that helps, let me know how you get on.
Drew
Related
I'm trying to get all files from firebase's storage through listAll.
By the way..
storageReference.listAll().addOnSuccessListener { listResult ->
val image_task : FileDownloadTask
for (fileRef in listResult.items) {
fileRef.downloadUrl.addOnSuccessListener { Uri ->
image_list.add(Uri.toString())
println("size1 : " + image_list.size)
}
}
println("size2 : " + image_list.size)
}//addOnSuccessListener
enter image description here
Why is the execution order like this?
How do I solve it??
When you add a listener or callback to something, the code inside the listener will not be called until sometime later. Everything else in the current function will happen first.
You are adding listeners for each item using your for loop. No code in the listeners is running yet. Then your "size2" println call is made after the for loop. At some later time, all your listeners will fire.
If you want asynchronous code like this to be written sequentially, then you need to use coroutines. That's a huge topic, but your code would look something like this (but probably a little more involved than this if you want to properly handle errors). I'm using lifecycleScope from an Android Activity or Fragment for this example. If you're not on Android, you need to use some other CoroutineScope.
The calls to await() are an alternative to adding success and failure listeners. await() suspends the coroutine and then returns a result or throws an exception on failure.
lifecycleScope.launch {
val results = try {
storageReference.listAll().await()
} catch (e: Exception) {
println("Failed to get list: ${e.message}")
return#launch
}
val uris = try {
results.map { it.downloadUrl.await().toString() }
} catch (e: Exception) {
println("Failed to get at least one URI: ${e.message}")
return#launch
}
image_list.addAll(uris)
}
There is nothing wrong with the execution order here.
fileRef.downloadUrl.addOnSuccessListener { Uri ->
the downloadUrl is an asynchronous action which means it doesn't wait for the action to actually complete in order to move along with the code.
You receive the result with the success listener (at least in this case)
If you want to deal with it in a sequential way, look at coroutines.
I have this static (companion object) function to download event information from Firebase Firestore and event images from Firebase Storage:
fun downloadEventInformationAndImages() {
FirebaseFirestore.getInstance().collection("events").document(downloadedEventID)
.get().addOnSuccessListener { snap ->
//Download Event Information Here
//Do stuff
GlobalScope.launch(Dispatchers.Main) {
//Download Event Images Here
val downloadEventImage = FirebaseStorage.getInstance().reference.child("Images/Events/$eventID/eventPhoto.jpeg")
.getBytes(1024 * 1024).asDeferred()
val downloadEventFounderImage = FirebaseStorage.getInstance().reference.child("Images/Users/$founderID/profilePhoto.jpeg")
.getBytes(1024 * 1024).asDeferred()
try {
val downloadedImages = mutableListOf<ByteArray>(
downloadEventImage.await(),
downloadEventFounderImage.await())
// Update stuff on UI
} catch(e: StorageException) {
// Error handling
}
}.addOnFailureListener { exception ->
// Error handling
}
}
}
What I want to do is avoid using GlobalScope but when I tried to add runBlocking to downloadEventInformationAndImages():
fun downloadEventInformationAndImages() = runBlocking {
// Do stuff
launch(Dispatchers.Main) {
it didn't work (It didn't wait Firebase to finish downloading - then I moved runBlocking to inside of function, also didn't work). How can I avoid using GlobalScope? Thanks in advance.
The best option I see here is to pass a CoroutineScope as a parameter of downloadEventInformationAndImages. So that would be
fun downloadEventInformationAndImages(scope: CoroutineScope) {
FirebaseFirestore.getInstance().collection("events").document(downloadedEventID)
.get().addOnSuccessListener { snap ->
//Download Event Information Here
//Do stuff
scope.launch(Dispatchers.Main) { ... }
}
}
The one thing you have to be careful is that every coroutine you launch here is now launched in the scope you pass in, which means that if it fails or is cancelled, it'll also cancel any parent coroutines. To understand how to deal with this, you should check the documentation for Jobs. On the other hand, you can also build your CoroutineScope with a SupervisorJob (mentioned in the documentation link above), where child coroutines fail without affecting the parents. Finally, it's also good practice to cleanup your CoroutineScope when the object that owns it reaches the end of its lifecycle. This will avoid possible memory leaks. The cleanup can be done either with scope.cancel() or scope.coroutineContext.cancelChildren(). The first one terminates the scope's job (which gets propagated to all child jobs), and the second one just cancels any child jobs that may exist. I suggest you spend some of your time just reading articles or even documentation about coroutines, because there are a lot of nuances :)
You can write your function as CoroutineScope extension function:
fun CoroutineScope.downloadEventInformationAndImages() {
...
launch(Dispatchers.Main) {
...
}
and call it from ViewModel or some other place with scope:
uiScope.downloadEventInformationAndImages()
Let's say that two users do changes to the same document while offline, but in different sections of the document. If user 2 goes back online after user 1, will the changes made by user 1 be lost?
In my database, each row contains a JS object, and one property of this object is an array. This array is bound to a series of check-boxes on the interface. What I would like is that if two users do changes to those check-boxes, the latest change is kept for each check-box individually, based on the time the when the change was made, not the time when the syncing occurred. Is GroundDB the appropriate tool to achieve this? Is there any mean to add an event handler in which I can add some logic that would be triggered when syncing occurs, and that would take care of the merging ?
The short answer is "yes" none of the ground db versions have conflict resolution since the logic is custom depending on the behaviour of conflict resolution eg. if you want to automate or involve the user.
The old Ground DB simply relied on Meteor's conflict resolution (latest data to the server wins) I'm guessing you can see some issues with that depending on the order of when which client comes online.
Ground db II doesn't have method resume it's more or less just a way to cache data offline. It's observing on an observable source.
I guess you could create a middleware observer for GDB II - one that checks the local data before doing the update and update the client or/and call the server to update the server data. This way you would have a way to handle conflicts.
I think to remember writing some code that supported "deletedAt"/"updatedAt" for some types of conflict handling, but again a conflict handler should be custom for the most part. (opening the door for reusable conflict handlers might be useful)
Especially knowing when data is removed can be tricky if you don't "soft" delete via something like using a "deletedAt" entity.
The "rc" branch is currently grounddb-caching-2016 version "2.0.0-rc.4",
I was thinking about something like:
(mind it's not tested, written directly in SO)
// Create the grounded collection
foo = new Ground.Collection('test');
// Make it observe a source (it's aware of createdAt/updatedAt and
// removedAt entities)
foo.observeSource(bar.find());
bar.find() returns a cursor with a function observe our middleware should do the same. Let's create a createMiddleWare helper for it:
function createMiddleWare(source, middleware) {
const cursor = (typeof (source||{}).observe === 'function') ? source : source.find();
return {
observe: function(observerHandle) {
const sourceObserverHandle = cursor.observe({
added: doc => {
middleware.added.call(observerHandle, doc);
},
updated: (doc, oldDoc) => {
middleware.updated.call(observerHandle, doc, oldDoc);
},
removed: doc => {
middleware.removed.call(observerHandle, doc);
},
});
// Return stop handle
return sourceObserverHandle;
}
};
}
Usage:
foo = new Ground.Collection('test');
foo.observeSource(createMiddleware(bar.find(), {
added: function(doc) {
// just pass it through
this.added(doc);
},
updated: function(doc, oldDoc) {
const fooDoc = foo.findOne(doc._id);
// Example of a simple conflict handler:
if (fooDoc && doc.updatedAt < fooDoc.updatedAt) {
// Seems like the foo doc is newer? lets update the server...
// (we'll just use the regular bar, since thats the meteor
// collection and foo is the grounded data
bar.update(doc._id, fooDoc);
} else {
// pass through
this.updated(doc, oldDoc);
}
},
removed: function(doc) {
// again just pass through for now
this.removed(doc);
}
}));
Here is the problem :
I am currently programming a chatapp based on what i found on github (https://github.com/sasikanth513/chatDemo)
I am refactoring it with iron-router.
When I go to the page (clicking on the link) I get an existing chatroom (that's what I want)
When I refresh the page (F5) I get a new created chatroom ! (what i want is getting the existing chatroom ...)
Here is the code in ironrouter :
Router.route('/chatroom', {
name: 'chatroom',
data: function() {
var currentId = Session.get('currentId'); //id of the other person
var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
console.log(res);
if(res){
Session.set("roomid",res._id);
}
else{
var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
Session.set('roomid',newRoom);
}
}
});
You can find my github repo with the whole project : https://github.com/balibou/textr
Thanx a lot !
Your route data depends on Session variables which will be erased after a refresh. You have a few options but the easiest would be to put the room id directly into the route: '/chatroom/:_id'. Then you can use this.params._id to fetch the appropriate ChatRooms document. Note that you could still keep '/chatroom' for cases where the room doesn't exist, however you'd need to redirect to '/chatroom/:_id' after the insert.
In meteor, the Session object is empty when the client starts, and loading/refreshing the page via HTTP "restarts" the client. To deal with this issue, you could persist the user's correspondent id in a Meteor.user attribute, so that you could easily do:
Router.route('/chatroom', {
name: 'chatroom',
data: function() {
var currentId = Meteor.user().profile.correspondentId;
var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
console.log(res);
if(res){
Session.set("roomid",res._id);
}
else{
var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
Session.set('roomid',newRoom);
}
}
});
This would work, with the proper permissions, but I would recommend not allowing the direct update of that value on the client (I don't know if you want users to be able to override their correspondentId). So if you want to secure this process, replace all that code with a server method call, where your updates are safer.
Another (and more common case) solution was given by David Weldon, if you don't mind having ids in your URL (and therefore not a single url)
I'm writing an application based on ember-data, it loads up all of its data asynchronously. However, the didLoad function does not get called until find is used. For example:
App = Ember.Application.create();
App.Store = DS.Store.create({revision: 3});
App.Thing = DS.Model.extend({
didLoad: function(){
alert("I loaded " + this.get('id'));
}
});
App.Store.load(App.Thing,{id: "foo"});
...will not trigger the alert, and findAll will not return the model. However, when I run:
App.Store.find(App.Thing,"foo");
The didLoad function will trigger, and it can be found with App.Store.findAll(App.Thing).
What's going on?
The ember-data source code explains it well:
// A record enters this state when the store askes
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: DS.State.create({
// TRANSITIONS
exit: function(manager) {
var record = get(manager, 'record');
record.fire('didLoad');
},
// EVENTS
didChangeData: function(manager, data) {
didChangeData(manager);
manager.send('loadedData');
},
loadedData: function(manager) {
manager.goToState('loaded');
}
}),
this means that 'didLoad' will only be triggered when the record was loaded via the adapter.
The 'find' method asks the adapter for the data - this looks it up in the pool of currently available data hashes and in your case finds it, because you already provided it. In other cases however the data maybe does not exist locally in the browser but remain on the server, which would trigger an ajax request in the adapter to fetch it.
So 'didLoad' currently only works in combination with an adapter (e.g: find)
But I totally agree with you that this should be changed since triggering 'didLoad' on models that are loaded vai Store.load seems pretty obvious ;-)