What can cause Bonjour to not call me back during browsing? - iphone

I have a rather popular Bonjour-based application in App Store. It works perfectly, but around 0.2% of my users report a bizarre bug: "no arrows appear on the edges of the screen, so I can't share stuff with other people!". Needless to say, displaying these arrows is tied to the browsing of a particular Bonjour service on the local domain.
The problem is, the Apple review team seems to intermittently happen to be in this 0.2%. This isn't good for review results, as you might imagine. No matter how much I try, I cannot reproduce this bug.
From the few logs I have, it looks like my app is running correctly, just not receiving NSNetServiceBrowser delegate calls. What can cause this?
Things I've tried:
Having a shorter service name < 14 chars in length to be in spec.
Publishing on #"local." rather than #"" (aka Go Look For The Default Registration Domain). My app is rather useless on a wide-area network anyway.
Things I haven't tried: restarting the browsing machinery periodically. (I have two browsers, though, one looking for the legacy longer name, one for the new shorter one.)
What to do?

There are many areas where things can go wrong. Since the NSNetService instance provided to your delegate methods is autoreleased, you need to retain it if you plan on reusing it out of scope for that method. Most people will add it to an NSMutableArray or NSMutableDictionary so that it is automatically retained, and only autoreleased when removed from the collection. If that is the case for your code, make sure that you have properly initialized your collection before adding the object. Since messages to nil are perfectly ok, you may be sending the addObject:netService message to nil. You will not receive an obvious indication that you never initialized your array or dictionary, and it will appear as though everything is working just fine…except that delegate messages “mysteriously” don’t fire off when peers change status, when you try to connect to one, etc. This crops up often enough in Bonjour troubleshooting that I would recommend it as the first place to start your troubleshooting. It happens to the best of us.
One easily missed problem for apps running network code on a background thread: throwing an un-handled exception on that thread. This can occur without crashing your whole app due to Cocoa/Unix’s rules on threading. If your networking code “just stops working for no reason,” then you may want to check your iPhones Console and logs for error messages. Make sure you have set a breakpoint on the objc_exception_throw symbol.
For more, read the full article "Troubleshooting Bonjour Networking for the iPhone" at my dev blog.

Related

EXC_BAD_ACCESS and Address Sanitizer what's the next step?

Have an app that's an iOS app with a Messages extension app. They share a significant amount of code related to calculating & editing the dimensions of some specialized objects and then using that to create paths for drawing.
The app was running perfectly. A build of the Messages app crashed with EXC_BAD_ACCESS code=2, seemingly within the code that's shared. No luck debugging it, as the location of the crash seemed to bounce around as I added log statements and refactored the code.
So I focused on the main app. First try was turning on Address Sanitizer, and that created the crashes discussed below. Then I edited the scheme to look for Zombies, and none were identified, including in Instruments. No memory leaks or other obvious allocation errors via Instruments. I edited the scheme to turn on Malloc Scribble, Malloc Guard Edges, and Guard Malloc, and the app ran fine with no crash or console log message.
So back to Address Sanitizer, which is the only option that caused the main app to crash, and it crashed in the same area as the Messages app. I figured if I solved one, I might solve both, and the app might be easier to debug without the complication of being an extension.
Every link I searched and read seemed to say that these Xcode diagnostics will (or should) identify the offending code, and in years of writing Swift, that's the typical case. This one has me stumped.
The main view controller is a UICollectionViewController, and the crash occurs at the very first collectionView(:cellForItemAt) call. There's nothing unusual about the other delegate calls, afaik, with normal (and accurate) counts and sizes. (And again, this is just with Address Sanitizer.) After getting the reusable cell, I call getObjectEffects with some default values (the app is more complex, but it crashed also on this ultra-simple hard-coded values case too, so I'm keeping the debugging as simple as possible), and the EXC_BAD_ACCESS is identified for the func definition of that function.
That's what stumps me. It's not identifying code where there's an assignment or allocation, but a func statement. And the parameters are Int and Bool. And there's zero output to the console, where I've also tried (lldb) command script import lldb.macosx.heap and (lldb) malloc_info —type 0x... with no result. As mentioned, I tried Zombies and the other Xcode memory management diagnostics with no insight into why Address Sanitizer is crashing at a func statement with an EXC_BAD_ACCESS, and I'm not sure how to diagnose this further.
What have I missed? Thanks for any insights.
Edit: Eventually made progress by switching code around and looking for different results. The eventual 'solution' is illogical in that I can't figure out how it should logically create any different result, but it does. And since it offers no insight into the original question of how to diagnose the cause of the EXC_BAD_ACCESS, I won't belabor it further here. For now, it'll be a 'solved' mystery.

Realm - RJSRealmDelegate.changes_available assert(0) causing crash

We are building a React-Native iOS app that needs to access our realms natively as well as via RN.
We have writing working correctly from our UI and can load the data in our background Swift service, but after the write, The changes_available method in js_realm.cpp is firing which contains assert(0) which is causing the app to crash/hang in debug. What do we need to be doing to prevent that method from firing?
Update: A release was just made (0.11.1) which should prevent this crash from occurring. Note that notifications across bindings have not yet been tested and may not work.
This method gets called when changes are made externally to a Realm from another process or thread. In your case it sounds like writes made from the swift apis are causing this method to get called. The ReactNative binding was written with the assumption that everything would be done from a single thread without considering the use of other language bindings being used simultaneously.
As is the only thing you can to do prevent this is to not make a write in Swift while a Realm is open in JS. One way to do this would be to call Realm.close after every use, although this may perform poorly.
In the near term we can also do a point release to remove the assert(0) - this will prevent the crash/hang, but notifications for changes made in Swift wont work without additional changes. Can't give an estimate of when we can get cross language notifications working properly.

Why use the Bundle when you can just use the Application?

I'm reading this article on how to : correctly retain variable state in Android and I'm reminded that I've never gotten a good answer (and can't find one here) for why it's better to tussle with the Bundle (which isn't a HUGE hassle, but definitely has its limitations) rather than just always have an Application overridden in your App, and just store all your persistent data members there. Is there some leakage risk? Is there a way that the memory can be released unexpectedly? I'm just not clear on this... it SEEMS like it's a totally reliable "attic" to all the Activities, and is the perfect place to store anything that you're worried might be reset when the user turns the device or suspends the app.
Am I wrong on this? Would love to get some clarity on what the true life cycle of the memory is in the Application.
Based on the answers below, let me extend my question.
Suppose I have an app that behaves differently based on an XML file that it loads at startup.
Specifically, the app is a user-info gathering app, and depending on the XML settings it will follow an open ended variety of paths (collecting info A, but not J, and offering Survey P, followed by an optional PhotoTaking opportunity etc.)
Ideally I don't have to store the details of this behavior path in a Bundle (god forbid) or a database (also ugly, but less so). I would load the XML, process it, and have the Application hold onto that structure, so I can refer to it for what to do next and how. If the app is paused and the Application is released, it's not *THAT big a hassle to check for null in my CustomFlow object (that is generated as per the XML) and re-instantiate it. It doesn't sound like this would happen all that often, anyway. Would this be a good example of where Application is the *best tool?
The question as to which method is better largely depends upon what information you are storing and need access to and who (which components, packages, etc.) needs access to that information. Additionally, settings like launchMode and configChanges which alter the lifecycle can help you to determine which method is best for you.
First, let me note, that I am a huge advocate for extending the Application object and often extend the Application class, but take everything stated here in its context as it is important to understand that there are circumstances where it simply is not beneficial.
On the Lifecycle of an Application: Chubbard mostly correctly stated that the Application has the same life as a Singleton component. While they are very close, there are some minute differences. The Application itself is TREATED as a Singleton by the OS and is alive for as long as ANY component is alive, including an AppWidget (which may exist in another app) or ContentResolver.
All of your components ultimately access the same object even if they are in multiple Tasks or Processes. However, this is not guaranteed to remain this way forever (as the Application is not ACTUALLY a Singleton), and is only guaranteed in the Google Android, rather than the manufacturer overridden releases. This means that certain things should be handled with care within the Application Object.
Your Application object will not die unless all of your components are killed as well. However, Android has the option to kill any number of components. What this means is that you are never guaranteed to have an Application object, but if any of your components are alive, there IS an Application to associate it to.
Another nice thing about Application is that it is not extricably bound to the components that are running. Your components are bound to it, though, making it extremely useful.
Things to Avoid in Application Object:
As per ususal, avoid static Contexts. In fact, often, you shouldn't store a Context in here at all, because the Application is a Context itself.
Most methods in here should be static, because you are not guaranteed to get the same Application object, even though its extremely likely.
If you override Application, the type of you data and methods store here will help you further determine whether you need to make a Singleton component or not.
Drawables and its derivatives are the most likely to "leak" if not taken care of, so it is also recommended that you avoid references to Drawables here as well.
Runtime State of any single component. This is because, again, you are not guaranteed to get back the same Application object. Additionally, none of the lifecycle events that occur in an Activity are available here.
Things to store in the Application (over Bundle)
The Application is an awesome place to store data and methods that must be shared between components, especially if you have multiple entry points (multiple components that can be started and run aside from a launch activity). In all of my Applications, for instance, I place my DEBUG tags and Log code.
If you have a ContentProvider or BroadcastReceiver, this makes Application even more ideal because these have small lifecycles that are not "renewable" like the Activity or AppWidgetProvider and can now access those data or methods.
Preferences are used to determine, typically, run options over multiple runs, so this can be a great place to handle your SharedPreferences, for instance, with one access rather than one per component. In fact, anything that "persists" across multiple runs is great to access here.
Finally, one major overlooked advantage is that you can store and organize your Constants here without having to load another class or object, because your Application is always running if one of your components is. This is especially useful for Intent Actions and Exception Messages and other similar types of constants.
Things to store in Bundle rather than Application
Run-time state that is dependent upon the presence or state of a single component or single component run. Additionally, anything that is dependant upon the display state, orientation, or similar Android Services is not preferrable here. This is because Application is never notified of these changes. Finally, anything that depends upon notification from that Android System should not be placed here, such as reaction to Lifecycle events.
And.... Elsewhere
In regard to other data that needs to be persisted, you always have databases, network servers, and the File System. Use them as you always would have.
As useful and overlooked as the Application is, a good understanding is important as it is not ideal. Hopefully, these clarifications will give you a little understanding as to why gurus encourage one way over the other. Understand that many developers have similar needs and most instruction is based on what techniques and knowledge a majority of the community has. Nothing that Google says applies to all programmer's needs and there is a reason that the Application was not declared Final.
Remember, there is a reason Android needs to be able to kill your components. And the primary reason is memory, not processing. By utilizing the Application as described above and developing the appropriate methods to persist the appropriate information, you can build stronger apps that are considerate to the System, the User, its sibling components AND other developers. Utilizing the information that everyone here has provided should give you some great guidance as to how and when to extend your Application.
Hope this helps,
FuzzicalLogic
I prefer to subclass Application and point my manifest to that. I think that's the sane way of coding android although the Android architects from Google think you should use Singletons (eek) to do that. Singletons have the same lifetime as Application so everything that applies to them applies to Application except much less dependency mess Singletons create. Essentially they don't even use bundles. I think using subclass Application has dramatically made programming in Android much faster with far less hassle.
Now for the downside. Your application can be shutdown should the phone need more memory or your Application goes into the background. That could mean the user answered the phone or checked their email. So for example, say you have an Activity that forces the user to login to get a token that other Activities will use to make server calls. That's something you might store in your service object (not android service just a class that sends network calls to your server) that you store in your subclass of Application. Well if your Application gets shutdown you'll loose that token, and when the user clicks the back button your user might return to an Activity that assumes you are already authenticated and boom your service class fails to work.
So what can you do? Continue to use Bundle awfulness? Well no you could easily store security tokens into the bundle (although there might be some security issues with that depending on how this works for your app), or you have to code your Activities to not assume a specific state the Application is in. I had to check for a loss of the token and redirect the user back to the login screen when that happens. But, depending on how much state your Application object holds this could be tricky. But keep in mind your Application can know when it's being shutdown and persist it's internal state to a bundle. That at least allows you to keep your Objects in memory for 99% of the time your Application, and only save/restore when it gets shutdown rather than constantly serializing and deserializing with boiler plate code whenever you move between Activities. Using Application lets you centralize how your program can be brought up and shutdown, and since it normally lives longer than any one activity it can reduce the need for the program to reconstitute the guts of your App as the user moves between Activities. That makes your code cleaner by keeping out details of the app from every Activity, reduces overhead if your Application is already built, shares common instances/code, and allows Activities to be reclaimed without loosing your program all together. All good programs need a centralized hub that is the core, and subclassing Application gives you that while allowing you to participate in the Android lifecycle.
My personal favorite is to use http://flexjson.sourceforge.net/ to serialize my Java objects into bundles as JSON if I need to send objects around or save them. Far easier than writing to sqlite DB when all you need to do is persist data. And nice when sending data between two Activities using objects instead of broken apart primitives.
Remember by centralizing your model in the Application you create a place to share code between multiple Activities so you can always delegate an Activities persistence to an object in the Application by hooking the onPause() as well allowing persistence to be centrally located.
The short answer is: use bundles as it makes saving your state out when you're backgrounded easier. Also, it's complicated.
The long answer:
My understanding is, as soon as you Activity's onPause method is called (and onSaveInstanceState which gives you a bundle into which you should store your Activity's data) your process can be terminated without further warning. Later, when the user comes back to your application, your activity is given an onCreate call with that original bundle from which to restore its state. This will happen to all your activitys in what was your original stack.
Being able to restore your state from the bundle (which Android will save for you as your process goes away) is how Android maintain's the myth of multi-tasking. If you don't dump your activity's state out to a bundle each time onSaveInstanceState is called, your app will look like it's been restarted when the user may have just switched out for a second. This can be especially troubling when the system is resource constrained as the system would need to kill off processes more often in order to keep the device running quickly
Why the Application can be Bad
The Application does not actually get a chance to save any of its data if the process is shut down. It does have an onDestroy method but the docs will tell you that this actually never gets called by the system on an actual device. This means that, in the constrained case I mentioned above, any incidental information about what's going on within an Activity (if you've saved it in the Application) will be lost if the process is ended.
Developer's often miss this case (and it can be really annoying for users) because they're either running on a dev phone which never gets hit with using many applications at the same time. We're also never using the app for a while, then switching to another application and, after a while, switching back again.

CFHost DNS Resolution - When is it OK to use synchronous API?

I went to the iPhone Developer Tech Talk a few months ago and asked one of the gurus there about the lack of NSHost on the iPhone. Some code I was porting to the iPhone made significant use of NSHost throughout its networking code.
I was told that NSHost is on the iPhone, but its private. I was also told that NSHost is a synchronous API and that I shouldn't use it anyway. (If anyone could elaborate on why it shouldn't be used, as a bonus, that'd be great.)
I can see the caveats of using synchronous API's on the main thread in that they'll block until complete - and that's never a good thing with network code because there are so many factors that could cause the API to block the thread for a significant amount of time.
My solution was to write a wrapper around CFHost's asynchronous resolution functions.
The result works quite well, and I'm considering releasing it into the public domain.
But my question is this: Say my app only resolves a hostname once per run, during the connecting phase, and then cache's it for the rest of the session. During the time it is resolving, a modal screen is shown telling the user "Connecting" with a nice spinner.
Does it really matter whether or not the resolution is asynchronous?? The user has to wait to connect anyway, and the resolution is only done on the first connection. Subsequent connections use the cached result of the resolution.
When is it OK to be synchronous and when should things be asynchronous?
Your nice spinner won't spin, since the UI will get blocked as well during the synchronous call. Sure, you can make the call on a separate thread, but then you're doing essentially the same thing as the asynchronous call.

How can I remove UIApplicationMain from an iPhone application?

I'm trying to port a game library over to the iPhone. Unlike SDL, this library doesn't take full control of your main() function, it's communicated with via quickly-returning functions from your own code. So, for example, obvious pseudocode:
int main() {
library_init();
// game init code here
while(we_have_not_quit_the_game) {
library_message_loop();
library_init_render();
// render stuff
library_end_render();
// update game state
}
library_shutdown();
}
iPhone makes this difficult, as it requires that you call a UIApplicationMain function that never returns. There's simply no way I could ever get back to the user code after library_init();.
I'm not convinced it's necessary - there's NSRunLoop which supposedly could be used to handle the events. I don't know if UIApplicationMain does anything else of importance, however. (Note that I have no plans to use .nib files, which is the only other thing I've found that UIApplicationMain does.)
I've got three real ideas that I can think of, but they're all a major implementation effort so I'd like to know if anyone has experience with this before I burn a day trying doomed ideas.
In Init, spawn a new thread, run UIApplicationMain in that thread. Either communicate all events across threads (ugh) or just put the UIApplicationMain thread to sleep and use a CFRunLoop in the main thread. I've heard UIApplicationMain does not like being run in a different thread, however.
Ignore UIApplicationMain entirely, just use NSRunLoop. Am I going to be missing important iPhone setup? Who knows!
Do something horrifying with longjmp() to leap out of the UIApplicationMain code after setup, pray that it doesn't do anything important during teardown.
Suggestions?
Looks like I'm answering my own question here! I'm not accepting my answer until I've been able to both test it on real hardware and get it into the app store. That said, I'll keep my Most Up-To-Date Info here, including which options didn't work.
Idea #1: It turns out that each NSRunLoop is thread-specific. If I create a UIApplicationMain in a separate thread, it doesn't get any messages. As a side effect this makes it impossible to determine when it's finished initializing, so if there's anything non-threadsafe it does, it just won't work. I may be able to send it a message across threads to figure out when it's finished initializing, but for now I'm calling this a dead end.
Idea #2: UIApplicationMain does a lot of subtle stuff. I'm not sure what it's restricted to, but I was unable to make anything work without involving UIApplicationMain. Idea #2 is right out.
Idea #3: Receiving the OS signals is important - you need to know if there's a phone-call overlay, or whether you're about to exit. On top of that, some of the setup messages seem vital in order to start the app properly. I was unable to find any method to keep messages being sent without being inside UIApplicationMain. The only options I came up with were NSRunLoop and CFRunLoop. Neither one worked - the messages didn't come in like I wanted. I may not be using these right, but in any case, Idea #3 is out.
Brand-new crazy Idea #4: It's possible to use setjmp/longjmp to fake coroutines in C/C++. The trick is to first set the stack pointer to some value that won't clobber anything important, then start your second routine, then jump back and forth, pretending like you have two stacks. Things get a tiny bit messy if your "second coroutine" decides to return from its main function, but luckily, UIApplicationMain never returns, so this isn't a problem.
I don't know if there's a way to set the stack pointer explicitly on real hardware, say, to a chunk of data that I allocated on the fly. Luckily, it doesn't matter. The iPhone has a 1MB stack by default, which is easily enough to fit a few coroutines in.
What I'm currently doing is using alloca() to push the stack pointer ahead by 768 kilobytes, then spawning UIApplicationMain, then using setjmp/longjmp to bounce back and forth between my "UI routine" and my "main routine". So far, this is working.
Caveats:
It's impossible to know when the "UI routine" has no messages to handle, and when it has no messages to handle, it will just block indefinitely until that's no longer the case. I'm solving this by making a timer that triggers every 0.1 milliseconds. Every time the timer triggers, I drop out to my "main routine", do a single game loop, then head back into the "UI routine" for another timer tick. Reading the documentation indicates that it won't stack up "timer calls" indefinitely. I do seem to get the "terminate" message appropriately, though I haven't managed to test it thoroughly yet, and I haven't tested any other important messages. (Luckily, there's only four messages total, and one of them is setup-related.)
Most modern OSes won't allocate the entire stack at once. The iPhone is probably one of these. What I don't know is whether bumping the stack pointer 3/4 of a meg forward will allocate everything "behind it", so to speak. If so, I may be effectively wasting 3/4 of a meg of RAM, which, on the iPhone, is significant. This could be handled by bumping the pointer forward a smaller amount, but this is really courting stack size disaster - it effectively limits your stack to however far you bump the pointer ahead, and you'll have to figure this out in advance. Some sentinel data in the stack, coupled with good monitoring and a logging system for stack size issues, can probably solve this, but it's a nontrivial issue. (Alternatively, if I can figure out how to muck with the stack pointer directly on the native hardware, I can just malloc()/new[] a few kilobytes, point the stack pointer at it, and use it as my new stack. I'll have to figure out how much space it needs but I doubt it'll be much, considering that it's not doing very much.)
This is currently untested on the actual hardware (give it a week or two, I got another project to finish first.)
I have no idea whether Apple will figure out what I'm doing and slap a giant REJECTED sticker on it when I try submitting to the app store. This is, shall we say, slightly outside their intentions for the API. Fingers crossed.
I'll keep this post updated, and officially accept it once I've verified that it, you know, works.
Late update: I got distracted by a variety of other things. Since then, I've had a few changes that make me far less interested in Apple development. My current approach showed no sign of not working, but I don't really have the motivation to keep fleshing it out. Sorry! If I ever change my mind I'll update this further, but Outlook Not So Good.
I know NSApplicationMain() reads Info.plist and does stuff to the app (like get the initial nib file) so I would guess that UIApplicationMain() does the same for iPhone (like get the initial status bar style, zoom the default.png image in etc.). That stuff isn't exposed anywhere else, so the functions it calls would still need to be run for the app to launch with out any side effects. You're only bet is to reverse engineer those and copy them (and hope that anything they do is in the public SDK).
Is the goal to take that main() function and have it work unmodified on the iPhone?
It would seem there's no way you're going to completely insulate the users of the library from thinking about the iPhone platform--they're going to have to deal with XCode for code signing and that sort of thing.
Given that, telling users they have to break their main() function up into a few pieces that you can call from applicationDidFinishLaunching and from an appropriate timer doesn't seem like it would inconvenience anybody much.
Why not start your game loop from within UIApplication? (Yes, you can't have it in main() but that shouldn't matter.) Some of the delegate messages are good candidates.