Posts in Technology (10)

The 21 best Mac tools for developers

At the most recent CocoaHeads meetup in Shanghai, I presented 21 of my favorite tools which I use on my Mac. These are not necessarily specific to iOS development, but they are all tried and tested tools which save me a few seconds, a few minutes or a few hours of my time.

Bartender ($15, keeps your Mac's menu bar tidy, by hiding lesser used icons in a separate menu.
Continue reading...

Building a WeChat (Weixin) robot

Matt presented a talk on Building a WeChat robot at Barcamp Shanghai Spring 2014! Here's a recap of the talk, as well as a link to download the source code of the robot.

If you'd like to skip the technical jargon and just play with the real bot, scan this QR code in WeChat and send our bot a message, or just search for "ReignDesign"!

Weixin Bot.006

Now, robots are cool, but building a real robot requires lots of hardware knowledge.

Weixin Bot.004

And one common topic you'll notice in today's talk is that I am quite lazy.

Weixin Bot.003

So when I say "robot" I'm talking about a robot you can build with software: a chatterbot. Send a message to a WeChat account, and get a message back.

Why WeChat? WeChat is ubiqituous in China, and so it's a great way of getting your service in front of as many people as possible, without them having to download another app.

Weixin Bot.005

Now you or I have personal WeChat accounts, but if we want to build a bot we need an official account. There are two types of these, Subscription Accounts and Service Accounts.

Weixin Bot.007

Subcription Accounts are best for marketing purposes. You have the ability to send up to 5 "broadcasts" each month to all your followers - perhaps if you are a restaurant, you want to announce some new specials. The downside of subscription accounts is they are hidden away in the WeChat interface inside the Subscription Accounts section.

Service Accounts are listed in the main WeChat friends list. You're only allowed to send one broadcast a month. But, any time someone sends you a message, you can reply to them immediately, and also send them messages for up to 48 hours. So, if you're trying to do customer service via WeChat, or build a bot, a Service Account is a great choice.

Here's the signup form for a WeChat official account (currently Chinese only).

Weixin Bot.008

You'll need to provide some basic information like name, email address, and which type of account you want. The two pieces of information that may require some effort are the 营业执照 (Company License) and 组织机构代码证 (Organization number). Right now you'll need to have a Chinese company license to apply for a WeChat official account.

After submitting all your data, be prepared to wait. It will take about 3 business days for your app to get approved.

Weixin Bot.009

One you're finally approved, you have access to the WeChat API. This comes in two flavours: basic API and advanced API. The basic API provides all that we need to build a basic chatterbot!

Weixin Bot.010

In the Developers section, you now need to provide a URL and Token. At the URL provided you now need to provide a simple web server. This will listen for requests from the WeChat server. So, for example every time someone sends you a message, you receive an HTTP request with the details of their message.

Weixin Bot.012

For our backend server we used a simple stack running on Heroku, with Node.js and Express, but you could use any language and framework, like Ruby on Rails, or PHP.

Weixin Bot.013

When you first register an application with WeChat they will send you an authorization request to your URL. This includes the token you provided earlier, plus various other OAuth credentials, and an parameter called "echo_str", which you should return if everything checks out OK.

As mentioned previously, I'm quite lazy, so to avoid having to figure out the authentication issues, I simply return the echo_str for ALL requests. This should not be recommended in a production application.

Weixin Bot.016

Now, each time you receive a message to your account, you'll get an HTTP request. You may be hoping for a nice JSON payload.

Weixin Bot.017

Unfortunately Tencent decided to use XML, and not very well structured XML at that.

Weixin Bot.018

Here's what a typical incoming message looks like.

Weixin Bot.019

You get a FromUserName and ToUserName. These are actually encrypted so you don't have access to the user's real WeChat ID. There's also a timestamp, the type of message (in this case text, but it could also be image, video or voice) and the text content.

To parse this in Node.js, we install an npm package called express-xml-bodyparser and configure Express to use it.

Weixin Bot.020

Next we implement a method to handle the request. We parse the values out of the XML...

Weixin Bot.021

Then we construct some XML to send back as a response. Notice that we've switched the to username and from username, to ensure the message gets sent back to the recipient. The text of our reply is "Thanks for sending me a message saying (original message)".

Weixin Bot.022

How does this work? Like this!

Weixin Bot.023

Now this is great, but of course version 1 of our robot is pretty stupid. How can we imbue our bot with some more intelligence?

To solve this I turned to the work of Joseph Weizenbaum.

Weixin Bot.024

He was a brilliant German-American computer scientist based at MIT. In 1966 he wrote a program called ELIZA. ELIZA was one of the first programs which tried to interpret and respond to natural language inputs from users.

It did this via some basic pattern matching. ELIZA could be fed with different scripts of patterns, and the most famous of these, called "DOCTOR", imitated a psychiatrist.

Weixin Bot.026

Here's ELIZA in action. You can see that ELIZA picks out certain words in a statement, and is able to formulate a reply using the words.

Weixin Bot.025

Now you're just talking nonsense!
> What makes you believe now I am just talking nonsense?

Weizenburg was surprised to discover that despite the primitiveness of the logic, users became quickly emotionally involved with interacting with ELIZA.

ELIZA is a fascinating episode in computing history, and I was delighted to see that the ELIZA logic is available as a npm module. That means integrating it into my bot was very simple.

First, install the module

Weixin Bot.027

Then, replace the reply logic with a new function.

Weixin Bot.028

Here's the code for replying. We keep a dictionary of ElizaBot objects. That way we can give each unique user who messages us their own instance. That means the message "memory" can be kept distinct.

If this is a new user, we set up a new ElizaBot for them, and request an initial phrase like "Please tell me your problem".

Weixin Bot.029

If this is an existing user, we simply call eliza.transform to get a suitable response, based on the last line of input (and previous inputs).

Weixin Bot.030

Let's see how this works:

Weixin Bot.031

There seems to be great potential for using ELIZA for people who are interested in app development services in Shanghai 😉

Weixin Bot.032

Of course, while this is a fun example, there's lots of cool stuff you could make with WeChat robots. A robot could return weather or air quality data on demand. If a user sends you a picture, you could do image processing on that picture and send them back something really creative. The only limit is your imagination!

Weixin Bot.034

To try out the ReignDesign bot, scan this QR code!


To download the source code, check out the project on GitHub

Interested in finding out more about what's possible with WeChat, mobile apps, or other new technologies like iBeacon? Contact us!

Ten Things You Need to Know About iBeacon

You may have recently heard a lot of buzz about iBeacon and Bluetooth Low Energy. At ReignDesign, we're helping our clients make sense of this new technology, and how it can be used to making great location-aware mobile experiences.


Kirsten Osolind, President and COO of re:invention consulting, recently said  “Beacon technology will improve the way consumers use smart phones and transform numerous industries by solving the indoor geo-location challenge. It has great potential to facilitate better mobile payments thereby disrupting the whole credit card ecosystem because of its range.”

We're compiled 10 interesting facts that you need to know about iBeacons.

1. iBeacons are tiny

iBeacons are very small. To give you an idea, here's a Lego man holding an iBeacon in the ReignDesign office. This means it's easy to hide an iBeacon discreetly in a store or at an event.

2. iBeacons have very long battery life

iBeacon uses the "Bluetooth Low Energy" technology. Low energy means that a iBeacon can run off a single standard lithium battery for 1-2 years. You don't need to worry about an external power supply.

3. Most modern smartphones support detecting iBeacons

iOS devices including the iPhone 4S, 5, 5C and 5S, the iPad 3 and later, iPad Mini, all support iBeacons. iBeacon is Apple's brand name for this technology, but iBeacons work fine with Android devices too! Many Android devices running Android 4.3 or later detect iBeacons, including the Samsung Galaxy S3/S4/S4 Mini, Samsung Galaxy Note 2/3, HTC One, Nexus 4, 5 and 7.

4. You don't need an internet connection

iBeacons use Bluetooth. A device with Bluetooth switched on can detect iBeacons in range and pop up a notification or unlock content, even if there is no Internet connection. Of course, the content needs to be already included in the app. If there is Internet available, the app can do more advanced things, such as pulling live content from a website in response to detecting an iBeacon.

5. iBeacons work well indoors

Most smartphones use "assisted GPS" to determine a user's location. This uses a combination of the satellite GPS system, and local wifi and cellular tower signals to obtain a location. This isn't ideal: GPS only works outdoors, and wifi/cellular location is very rough. AGPS can tell you you are in a shopping mall, but not which store you are in. iBeacon is perfect for this scenario. Each iBeacon has a range of about 30m. For example, in a shopping mall, an iBeacon could be placed above the entrance to each store. A shopping mall app could then tell the user which store they are located nearby.

6. Big brands are already using iBeacons

Major League Baseball (MLB) is the major league professional baseball organization in the US. MLB first installed iBeacon technology at Petco Park and Dodger Stadium. By Opening Day of the 2014 season, 20 ballparks were equipped using iBeacon technology. Baseball fans can use the iBeacons with the app At The Ballpark.

Westpac Banking Corporation is a major Australian bank. They're rolling out iBeacon technology in branches. iBeacon will be used to send customers alerts with special offers and other incentives on their device when they are in or near a branch.

Apple themselves are also finding ways to use to offer targeted information to passing users via app notifications or in-app content. Recently, Apple introduced physical iBeacons at its retail stores. Beacons are placed throughout the store and as a customer walks around, the beacons trigger messages to the customer’s iPhone. A customer can scan an item they want and pay for it from their phone using the Apple Store app; the app too uses beacon technology.

7. iBeacons need an app to work

An iBeacon simply broadcasts a number of identifiers. For example:

{ uuid = "74278BDA-B644-4520-8F0C-720EAF059935"; major = 65504; minor = 65505; }

Now if we want a user's device to do something interesting when this beacon is detected, like pop up a coupon for a store, or unlock a video, we need an app. If the user hasn't downloaded your app, they won't see your iBeacons. When the app is launched, it can register which beacons it is interested in, for example any beacons with uuid "74278BDA-B644-4520-8F0C-720EAF059935" could cause a notification to pop up.

8. When you get close to an iBeacon, you can pop open a notification, even if the app is not running

When a user with your app installs comes close to an iBeacon, your app is notified. What happens next depends if the user has your app open: If they don't have the app open, your app is launched in the background. You can still do certain tasks like popping up a local notification. unlock For example, imagine a restaurant installs iBeacons at the entrance to each store. Customers with the app installed can receive a notification when they arrive. In a more advanced scenario, the app could make a web request to check if there are any active promotions. Only if there is a promotion relevant to the current user would the app pop up a notification.

9. If your app is running, you can unlock content based on beacon location

If your app is running, you can not only detect the location of beacons, but even see how far away they are using "ranging". This opens up many exciting possibilities. For example, imagine guests at an auto show. Each car model has an iBeacon attached. When guests holding an iPhone or iPad approaches the car, a video in the app can automatically play.


10. Choose a partner who understands this technology.

iBeacons are a new technology, and it pays to choose the right partner. ReignDesign is already working with a number of brands and agencies in Shanghai and around the world in deploying iBeacon-enabled apps. We have iBeacons in our office right now, and we're happy to give you a demonstration of this exciting technology. Get in touch today!

Does your app contain, display or access third-party content?

Apple have recently added a new question into the iTunes Connect flow when submitting a new app, or an update to an existing app.

"Does your app contain, display or access third-party content?"

If you answer "No", you can continue with the submission, if you answer "Yes" you are asked a further question, "Do you have all necessary rights to that content or are you otherwise permitted to use it under the laws of each App Store territory in which your app is available (for example, fair use).

If you answer "Yes", you can continue, if you answer "No" you are shown a warning, and a link to the trademarks section of the App Store Guidelines.

This doesn't appear to be any new policy on Apple's part, but we can guess that Apple is planning to enforce the guidelines more strictly in future, in particular guideline 8.5:

8.5 Apps may not use protected third party material such as trademarks, copyrights, patents or violate 3rd party terms of use. Authorization to use such material must be provided upon request.

This seems most likely to affect apps which use the brand names or logos of other companies, for example apps which show fashion products, sports teams, TV network logos, etc. Be prepared to submit written documentation that you have the right to show such content, even in the past Apple has not rigorously required this.

Customizing individual share services in a ShareActionProvider on Android

In theory, sharing on Android is simple. Because of the system of Intents, you can prepare your shareable content, like an image, or text, and then easily show a list of installed apps which are able to handle this type of content. For example, if you’re sharing a photo, apps like Instagram, Twitter and the Gallery app will be available in the list. No additional coding is required for each sharing service!

  1. Intent i=new Intent(android.content.Intent.ACTION_SEND);
  2. i.setType("text/plain");
  3. i.putExtra(android.content.Intent.EXTRA_SUBJECT,"My cool app");
  4. i.putExtra(android.content.Intent.EXTRA_TEXT, "Here’s some content to share");
  5. startActivity(Intent.createChooser(i,"Share"));

But what if you want to customise the content depending on the chosen service? For example, if the user chooses Twitter you might want to shorten the text you’re sharing. Facebook on Android also has a long-running bug that means it won’t share text/plain content shared via an Intent… it only works for links.

Perhaps we’d like to use some different logic when our user clicks Facebook, for example using the Facebook Android SDK we could invoke an Open Graph sharing dialog.

Unfortunately, this is not easy. If you’ve followed the Android tutorial on adding an easy share action to the action bar then you’ll have a ShareActionProvider which creates a share button and dropdown for your action bar.


The documentation is rather contradictory about whether you can customise ShareActionProvider’s behaviour. There’s a promising looking listener called setOnShareTargetSelectedListener, described here:

Sets a listener to be notified when a share target has been selected. The listener can optionally decide to handle the selection and not rely on the default behaviour which is to launch the activity.

So we might think to check the type of the intent in the listener, and run some custom behaviour for certain share types.

However the documentation goes on to say that

"Modifying the intent is not permitted and any changes to the latter will be ignored. You should not handle the intent here. This callback aims to notify the client that a sharing is being performed, so the client can update the UI if necessary."

The return result is ignored. Always return false for consistency.

It turns out if we try to add some custom code in setOnShareTargetSelectedListener, the custom code is run, but the standard share intent is also launched :(

Luckily since Android is open source, we can dig around in the source code to find out what’s going on.

Here’s the source code for the ShareActionProvider class in the v7 support library on Github.

Notice the class at the bottom ShareActivityChooserModelPolicy, which calls the listener, but then returns false regardless. Returning true from this method would allow us to handle the intent, without invoking the default behaviour.

  1. private class ShareActivityChooserModelPolicy implements OnChooseActivityListener {
  2. @Override
  3. public boolean onChooseActivity(ActivityChooserModel host, Intent intent) {
  4. if (mOnShareTargetSelectedListener != null) {
  5. mOnShareTargetSelectedListener.onShareTargetSelected(ShareActionProvider.this,intent);
  6. }
  7. return false;
  8. }
  9. }

We can’t easily subclass ShareActionProvider to override this behaviour, but what we can do is make a complete copy of the class and implement our own custom behaviour!

Copy the entire source file into your app, changing the package declaration at the top, and optionally the class name, for example to RDShareActionProvider.

Implement a new listener

  2. private OnShareListener mOnShareListener; //also need to add getter and setter
  4. public interface OnShareListener {
  5. /**
  6. * Called when a share target has been selected. The client can
  7. * decide whether to perform some action before the sharing is
  8. * actually performed OR handle the action itself.
* * @param source The source of the notification. * @param intent The intent for launching the chosen share target. * @return Return true if you have handled the intent. */ public boolean willHandleShareTarget(RDShareActionProvider source, Intent intent); }

Time to re-implement the ShareActivityChooserModelPolicy using our new more powerful callback.

  2. private class ShareActivityChooserModelPolicy implements OnChooseActivityListener {
  3. @Override
  4. public boolean onChooseActivity(ActivityChooserModel host, Intent intent) {
  5. if (mOnShareListener != null) {
  6. boolean result = mOnShareListener.willHandleShareTarget(
  7. RDShareActionProvider.this, intent);
  8. return result;
  9. }
  10. return false;
  11. }
  12. }

We're in the home straight! Now we need to change the reference in the menu XML to our new class name.

  1. <item
  2. android:id="@+id/action_share"
  3. android:title="@string/menu_share"
  4. android:icon="@drawable/ic_action_share"
  5. myapp:showAsAction="always"
  6. myapp:actionProviderClass="com.myapp.RDShareActionProvider"

Finally we can implement our listener. We can check the package name of the intent, each sharer will have a different one, depending on the app. For Facebook, it’s com.facebook.katana.

  2. mShareActionProvider.setOnShareListener(new OnShareListener() {
  3. @Override
  4. public boolean willHandleShareTarget(RDShareActionProvider source, Intent intent) {
  5. if (intent.getComponent().getPackageName().equalsIgnoreCase("com.facebook.katana")) {
  6. //just showing a toast for now
  7. //we could also manually dispatch an intent, based on the original intent
  8. Toast.makeText(self, "Hey, you're trying to share to Facebook", Toast.LENGTH_LONG).show();
  9. return true;
  10. } else {
  11. return false; //default behaviour.
  12. }
  13. }
  14. });

Finally, we have control over individual sharers!