Keep Your iOS App Running in Background Forever

I’ve known many people in my life who have a nasty habit of leaving stuff they’re not using plugged into the wall, just wasting energy. My wife would be a prime example. She’s just not in the habit of unplugging it and changing your habits can be hard. Thus, I set out to create an iOS app to remind her to unplug the charger from the wall every time she unplugs the device from a power source.

One without knowledge of iOS development would imagine this to be a simple task. The logic is certainly simple. Notice the battery state go from “charging” or “full” to “unplugged?” Great, send a simple local notification. Otherwise, just keep monitoring the battery state. So what’s the issue? Apple doesn’t want to keep apps running in background.

The logic behind this is pretty reasonable. Apps running in the background drain battery life faster. Apps draining your battery life gives you a bad perception of the device, not the app, because the average consumer has no idea that it’s an app, yet alone which specific app, that’s making their battery life crappy. Thus, iOS won’t let your app run in the background but it does give you some options, such as push notifications, to provide some data to the user and prompt them to open the app again to get the full details.

This is reasonable, but the problem is that push notifications are driven by data coming from the internet. What if you just want to monitor something on the device (i.e. battery state)? Well, as far as I can tell you’re out of luck without using a hack.

The notable hacks are using location services, playing an inaudible sound, and VOIP. Location services really can drain your battery as GPS is power hungry. Playing an inaudible sound is a good option but your app’s going to die if you actually use your device to play audio/video (and most of us do). So the only option in my mind is to use the VOIP hack.

The logic behind allowing VOIP apps to run in the background forever is that they need to be able to receive calls at all times. Thus, generally iOS tries not to close these apps and as a failsafe if it does (due to running out of memory or a crash or just restarting your device) it’ll automatically relaunch it in the background without making the user do anything.

The VOIP hack takes advantage of this to work with any application that wants to run in the background forever. There’s scattered information online, particularly on stack overflow on how to do this but it’s poorly documented and I couldn’t even get it to work for my application without some changes. Thus, I wanted to put it out here as clearly as possible to help anyone else working on an application like mine that needs to monitor the device in the background.

The configuration:
The first thing you need to do is modify your app’s plist. Add the following settings.

  • Application does not run in background: NO
  • Required background modes: VOIP

This lets iOS know that your app will be running in the background and thus will ensure that if it’s terminated, iOS restarts it automatically for you.

The code:
First, we need to set up the code for when the application launches. In here we set up our background task (bgTask) and the block that’s called when our background task expires after 10 minutes (expirationHandler). The expiration handler block ends our background task and restarts it. Additionally, you’ll notice that we start the background task immediately (even if we’re about to go into active mode) because when the app is terminated and relaunched by iOS it doesn’t tell the app that it’s going into background mode.

Next, we set up the background job. The key piece here is the dispatch_async block. This is the work we’ll be doing in the background. In my case, the work is just a while loop that checks the battery and then sleeps for 1 second. For 10 minutes this while loop executes and then we see the expiration handler called.

What’s interesting is that even though the expiration handler is ending our task, the dispatch_async block keeps running. Thus, we set a flag in the expiration handler saying the job has expired and use that to trigger the while loop’s end. Finally, we have the expiration handler spin while it waits for the old job to do this and exit the dispatch_async block. If you don’t do this you’ll have multiple dispatch_async blocks running at once and your app will be terminated more quickly.

Lastly, remember that we started the background task as soon as the app launched. If you don’t want this to run when the app is active then do something in applicationDidBecomeActive to stop the task from running. In my case this just meant setting another flag to get the while loop to exit.

That’s it! From my limited testing this seems to work well and not have a huge effect on battery life. Let me know if it works for your app.

The one huge drawback of this approach (as well as any I’m aware of to create this sort of application) is that Apple would reject it from the app store. Thus, if you’re looking to create an app for yourself, your wife, your friends, etc. then this’ll get the job done, but if you want to get it out into the world you’re out of luck.

Thus, I’m doing the best I can by putting my app on GitHub. I’d love any feedback or contributions.

The Past Year’s Gadgets Were Boring… Except for the Wii U

This has been harped on by plenty of people particularly around Christmas when so many get into their “I must buy all of the things” mood and look for something, anything, to buy their best friend’s neighbor’s cousin but I wanted to add my voice to the chorus. When it comes to innovation in consumer gadgets this year didn’t have much to offer, at least as far as I could tell. Everyone released their latest version of the phone/tablet/phablet, we were given even more devices that connect to Netflix/Youtube/Pandora, and cars were given one-button interfaces to be more iPad-like (goody?).

The one exception in my mind was the Wii U. I try to get myself one thing a year just for fun and this year it was unquestionably going to be the Wii U. Why? Well, because nothing else looked interesting (oh sweet, my iPhone screen can be 1/2 inch taller and 1/4 inch thinner), and because I’ve always been a sucker for Nintendo games – especially Mario.

So I got the Wii U on day 1 and immediately loved it. The asymmetric gameplay in Nintendo Land is really interesting. It’s fun playing games where one player does something on the tablet screen while four others do something else using the standard old Wiimotes. For instance in Mario Chase one player using the tablet runs away from up to four others using the Wiimote. The player using the tablet uses a map to see where the other players are and try to avoid them while those using the Wiimotes have to look for the player to chase without a map.

It’s also great being able to play on the tablet screen. You can easily switch between the two depending on if someone else wants to use the TV. I especially took advantage of this with New Super Mario Brothers U.

Another interesting feature of the Wii U is the Miiverse. Miiverse is a social network specifically for Wii U. You can post short messages in communities for each game about your progress, what you liked, what you didn’t, ask for help, whatever you want. Plus you can post screen captures for the game and pictures you draw on the tablet. The pictures are black and white but the detail some people are able to put into them is just amazing. Scrolling through these posts can be a lot of fun.

While the games out now are fun they largely don’t take advantage of the technology as much as they could. This isn’t shocking as software always lags behind new hardware. I’m looking forward to the new games coming out this year and to the new innovation it brings.

3 Things I Wish I Knew Before Building a Hybrid iPad App

At the end of November, the company I work at, Mindflash, released an iPad app. We built it primarily in AngularJS with some native hooks where we needed them. I’m sure I’ll expand more on this in the future but here are 3 quick things I (and I’m sure all of my colleagues) wish I knew prior to starting on the project. Perhaps they’ll help your in your own future projects.


    iOS Safari chokes on iframes. We found iframes to be a constant source of pain causing seemingly every problem from using an inordinate amount of memory to making a vertically scrolling div rendered on the page completely outside of the iframe only scrollable by swiping horizontally (WAT!?!).

    Given the huge number of APIs that use iframes, you can find yourself running into this problem a lot. Even worse for us was that the way in which we were originally communicating from the WebView to the native app was by changing the URL of an iframe in our app. In the end we removed all dependencies on iframes aside from embedding YouTube videos and have never been happier.

  2. Serving your local app from file:// uses a lot more memory than from a web server
    I don’t understand why this is, but the difference is substantial. We saw a drop of around 20-25 MBs of memory usage which is huge on iOS and particularly on the iPad 1.

    So how does one serve their app from the iPad’s file system without using file://? By using an iPad-based HTTP server of course! We used the open source CocoaHTTPServer.

  3. The iPad 1 Is the new IE6
    It seems no matter what you do to improve your app’s reliability and performance it will crash on the iPad 1 much more often than any of the later generations. This is due in part to the tighter memory constraints but also due to the fact that many people’s iPad 1’s were hosed on upgrade to iOS 5. Check out this thread for one of many discussions on the issue.

    There are lots of reports of people primarily on the iPad 1 but also on the iPad 2 seeing Safari (and thus WebView) crashes with breathtaking frequency after upgrading to iOS 5. Since the only guaranteed solution is resetting the iPad with iOS 5, you’ll run into plenty of users who haven’t done that and have just lived with it and there’s nothing you can do about it.

I hope this helps anyone building a hybrid app today. We’ve been thrilled with our decision to architect it this way. Again, I’ll follow up with future posts on the development of our iPad app. Perhaps the next one will be on things I wish we knew how to do – like how the hell do YouTube and Netflix serve their streaming video so quickly?

Repercussions of a Biting Child

My son, Seth, is a biter. I can’t say this is entirely surprising given that I was one myself. Apparently I started sometime after 2 whereas Seth started just after his first birthday. Seth is now a couple months shy of 2 and after about 8 months of trying to change this behavior I sometimes wonder if we’re any closer to a solution than we were when it all started.

The issue with biting is that it can cause more harm to other children than any other common form of toddler acting out. The triggers for it are generally the same as those for pushing, hitting, and other toddler misbehavior. Generally, the toddler is upset about a situation – someone is playing with a toy he wants to play with, taking the attention of someone whose attention he desires, or generally inhabiting a space he’s deemed fit for him. The toddler reacts with his impulse and ouch, the other child is hurt.

This all can happen over the course of a couple of seconds so it can be very difficult to prevent even after the child has been discovered to be “known biter,” and until it’s happened a few times no one’s even looking for it. However, once it’s been, found you and your child will be invisibly marked with a scarlet B.

Your child is the biter and you’re the parent of a biter, and that is how you shall be known. I can’t speak too much to the psyche of the parent of a child who’s been bitten several times by your child (although Seth has been bitten a few times himself I clearly have a different perspective as a father of a biter), but I can take some educated guesses here. It seems they are consumed by the raw emotion of seeing their child hurt (there has been some broken skin but no one’s had to go to the hospital for this – just to give you some perspective). I can understand this but I wish they’d step away and think about it with a bit of empathy for our plight when they’ve cooled down and see that their child is fine and will heal. Based on what we hear from Seth’s teachers it does not seem that this ever happens.

So if this is you and you’re reading this (or just curious I guess) here’s what it’s like. As the parent of a biter you constantly struggle with trying out new ways to potentially “solve the problem.” You research for hours every time it happens trying to glean every possible reasoning behind it and how to instill in your child that it’s not acceptable behavior. You try to understand his triggers and how to avoid them. If your child doesn’t bite as often or as hard at home because the situations that bring it out of him don’t exist at home (i.e. there’s not a cadre of children running through my house sharing toys) you think of how you might be able to bring it out of him just to reinforce the discipline he receives from his teachers at home. And when you’ve done all of these things you start trying a few new things with the realization that in all likelihood none of them will work and he will probably “grow out of it” (what does that mean? I think it means they mature emotionally and have enough empathy to realize the harm it’s causing and stop and/or you can employ different disciplinary measures that work on older children to finally get them to stop).

In addition to all of the work you do trying to “solve the problem” you spend a tremendous amount of time feeling terrible. You feel terrible for the children being hurt by your child and their families. You feel terrible about your parenting ability because surely you should be able to stop this even though it’s considered common and normal in this developmental stage. And you feel terrible because you’re being ostracized as you and your child are never invited to various play dates and birthday parties. For some, including my parents when I was younger, you lose friends. In most pre-schools/daycares (fortunately not ours), your child is eventually kicked out and your life is completely upended.

So as the title of this post indicates there are many repercussions to having a biting child but they’re generally not felt be the children. Despite what many parents of children who’ve been bitten may think, most biters are and will be fine. There’s nothing wrong with them, they just act out in a way that can be much more harmful to other children than your standard pushing and hitting. And fortunately even the bites that break skin usually won’t scar. Only the time spent by the parents during this period of their child’s life will have any lasting impact.

One Year Anniversary

We’ve just about reached the one year anniversary of having moved to the bay area so it seems like a reasonable enough moment to reflect.

The Area
There’s a lot to love about living in the bay area. I love being within 45 minutes of 3 large cities and the beach. The weather here is perfect – rarely too hot or too cold. It can be a little rainy at times but it rarely rains all day and rarely rains more than a few days in a row. The people here are friendly and incredibly diverse. There are many beautiful parks and many nice areas in the smaller peninsula towns of Silicon Valley.

This area lives and breathes tech. I’ve heard it called a company town in this way like the film industry is for LA. Sure there are plenty of people who don’t work in tech, but a large number of them are supported by the industry. I love that there are meetups and tech talks virtually every night somewhere in the valley or SF (not that I go anywhere near that often but at least I can pick a couple nights a month to attend). They’re hugely informative as well as a nice way to meet people, and the fact that most have free food/booze doesn’t hurt.

Although I love the area, there are downsides. It’s ungodly expensive to live here and the traffic can drive you crazy. However, if you can afford the lifestyle – which can definitely be a stretch for us – it’s worth it. One additional negative which we hope to fix at some point is that Menlo Park, the Silicon Valley town in which we live, is awful. It’s even more expensive than the bay area average, it’s not exactly filled with young people, and it’s quite boring compared to all of the other towns.

The Family
There’s certainly a lot more work out here for Erica but it’s still challenging for her to find everything she wants out of a job while also meeting her parental responsibilities. This is due to her industry (food) and how the people who work in it are treated like shit (I’m sure I’ll rant on that in another post). That said, she’s at least somewhat using her skills and interacting with adults again and that’s a positive step.

Seth started in daycare for 6 months and moved to a pre-school program at 18 months. He’s really thrived in it and absolutely loves it there. He’s made friends and gets to explore his creativity painting, drawing, baking, sculpting, etc. They also have music and dance classes. It’s really a great program. Since we moved here he’s gone from walking to running and from barely speaking at all to being a chatterbox who sings his favorite songs by himself (sometimes in medley form). His growth constantly amazes me.

It can still be very difficult being here alone without any family or other support but we make it work (sometimes barely). We’ve made some friends, many young and also with kids but that’s also still hard. It’s pretty difficult finding young people with kids who aren’t religious fundamentalists anywhere in this country, but it’s even more difficult here where it feels like the average person is having their first kid at age 43.

The Job
The job I took at Mindflash has been incredible. I’ve learned more there in the first year than I ever dreamed I would. The people I work with are great and the flexibility I’m given is amazing. I absolutely love coming into work every day. Prior to Mindflash I’d only worked at large companies but I’ve found here that my interests and skill set position me best to stay at startups for the foreseeable future.

The Future
Overall I’m very happy with our decision to move to the bay area a year ago. It hasn’t been without struggle but I think it’s been a great year. I’m looking forward to many more of them here. Happy New Year everyone.


Back to Blogging

Maybe it’s because I’ve been reading bullshit on Hacker News for a while but all of a sudden I feel like my thoughts are so important I need to blog about them. With this sense of self worth I should probably just run for Congress. All kidding aside I miss writing and this is a reasonable enough outlet to continue to write again. Plus, my colleagues are tired of me misusing Twitter by sending 3 tweets to get out a single thought.

I retitled my blog The Young Old Guy. Turns out an obscure song lyric from an …And You Will Know Us by the Trail of Dead song isn’t the best description of what I’ll be writing about now. The lens through which I see the world and thus will be writing is that of a young parent. Being a parent makes you old (which I’m sure I’ll get into more in this blog) so that makes me a young old person.

More to come…