iOS: Throttling a piece of code that’s called way too often

This is a quick post because today is a workday, but I wanted to share this snippet in case anyone finds it useful. Take, for example, that you have a color picker, and you want to update a live OpenGL rendering view every time the color changes to have it reflect the color the user chose. This is great and all, but if the user drags along the color picker view and it sends out 120 “color changed” updates per second, it’s an unnecessary drain on resources.

This allows you to write code like:

self.colorPickerView.colorChangedBlock = BlockThrottler.throttleBlock(interval: 0.25) { [weak self] color in
// do things with the color
}

Continue reading “iOS: Throttling a piece of code that’s called way too often”

Advertisements

Identifying issues in an iOS app early with assertions

Crashes are a two-faced beast. One face makes you cower in fear because users absolutely hate crashes: a single crash during the first-time experience is enough to drive away users who don’t have a watertight reason to use the app.

The other face is that it might take months to recognize for what it is: crashes are a necessary manifestation of underlying issues that prevent even more confusing and debilitating bugs from rising up in the future.

Take this example: you have an app that lets a user generate a video on the web, automatically downloads it onto his camera roll so he can share it to other apps, and opens a share sheet that allows the user to share it to those apps. Then, it caches the location of the video on his device so that he doesn’t have to download it again. Continue reading “Identifying issues in an iOS app early with assertions”

Kotlin: Easily storing a list in SharedPreferences with Custom Accessors

SharedPreferences is at its core a simple tool with a deceptively verbose interface that weighs heavily on developer productivity. Kotlin on its own will not necessarily make Java-interfacing code pretty and concise, but you can apply a few particular concepts to create an elegant, downright easy-to-use solution to a common use-case:

Storing a list of strings that will persist across app sessions.

You can write code as if you have a regular old stored List<String> property, with the additional benefit that it is always in sync with SharedPreferences (*):

// Adding to a list
if (syncingSongIds.indexOf(song.id) == -1) {
    syncingSongIds += song.id
}

// Iterate through a list and do something with each element
syncingSongIds.forEach { id ->
    stopSyncing(id)
}

// Best of all: subtracting from a list
val intent = Intent(DONE_SYNCING) 
intent.putExtra("song", song)
sendBroadcast(intent) // send a broadcast that we're done syncing

syncingSongIds -= song.id // and remove the song id from the persisted list of syncing songs

If you’re interested, read on.

Continue reading “Kotlin: Easily storing a list in SharedPreferences with Custom Accessors”