Category Archives: iOS

Node server authenticate for iOS client using token

Authentication – POST for /api/authenticate using parameters ‘name’ and ‘password’

Here’s we authenticate by giving the server a name and password. If the name and password match the ones stored in the database, then we return it a token for the iOS client to use. Whenever that the iOS client needs to access a protected URL, we use that token.

Server side

/config.js

First notice that in the beginning of the file, we use set to have
superSecret name as an application setting name.

/server.js

We set the key ‘superSecret’ to match config.secret which is ‘ilovescotchyscotch’ in /config.js

Later we will use jwt’s sign function on this string along with the user object in order to create a token for the iOS client to use.

We use express’s router function to get variable apiRoutes. We prefix all routes with ‘/api’.

Then for POST on url /authenticate, we use mongoose’s model User to find if the user exist. If it does, it will then run the async method to see if the passwords match.

If the passwords match, then we use jwt’s sign function to return a token for the user to use. We wrap that token along with other string info in a json object and return it via the response object.

iOS client

We create NSDictionary with name and password key. Then we encode it into a NSString.

Notice we then call the URL ‘http://192.168.1.102:8080/api/authenticate’ with POST, and the json string in the body of the request.

After we POST this request, our server will hit the apiRoutes.post(‘/authenticate’, function(req, res) {…}) function, which uses jwt.sign(user, app.get(‘superSecret’)) to return a token for this particular user.

It returns:

res.json({
success: true,
message: ‘Enjoy your token!’,
token: token
});

Hence the server code, we see that the returned json object has 3 keys:
success, message, and token. Use the value from key token in order to authenticate yourself when doing updates and other restricted activities.

Using Token to authenticate itself and access protected URLs

Reading list of users using approved authentication

Now that we have the authentication, we need to use it to read protected data

In your server.js, put this code to protect your URLs:

So that when you hit

http://localhost:8080/api/users

You’ll get:

{“success”:false,”message”:”No token provided.”}

So as you can see a client that does not provide the correct token and user name cannot access that what http://localhost:8080/api/users has to offer.

Thus, we access it by using the token received earlier when we authenticated with our user name and password. We set the token and our username into the header of the request packet.

AppDelegate.m

As you can see, once you log in, use the token string to get info.

GetInfoConnection.h

GetInfoConnection.m

Notice how we set the request’s header with the user name and token value in the method getUserInfo.

These values are then sent to the server where they get processed by apiRoutes.use(function(req, res, next) {…}), which uses jwt.verify to verify if this username and token is valid.

Then the server passes it onto the next middleware layer, namely, apiRoutes.get(‘/users’, function(req, res) {…}) to have the database retrieve the valid user.

Full server code

iOS client consume node js web service

iOS client

Basically keep in mind that when you want to hit a local node js server, the address on the network from the iOS cient’s pov is 192.168.1.102.

You go to System Preferences > Wi-Fi (or Ethernet, or whatever you use to get internet connection ). Then on the right hand side, the status should say ‘connected’ and you’ll see something like “Wi-Fi is connected to TP-LINK_3DF056 and has the IP address 192.168.1.102.”

192.168.1.102 is the network address of the computer that’s running the node js server. Hence when iOS clients look for the server, they will need to hit that address.

We are simply trying to hit a url using GET, and expect json data back.

GET for /

Notice that we use “message” as the key for our json data because in our node code, we are returning a json object using the key “message”.

Node server

POST /setup with parameters ‘name’ and ‘password’

iOS client side

So we use NSDictionary to create dictionary object with keys name and password.
Then, we encode it into a NSUTF8StringEncoding string.

We then use that dictionary string and set it as Http body using setHTTPBody for the request object. We also set our http method to POST using setHTTPMethod on the request object.

Node server side

Checking mongo db via terminal

Open your terminal and type in

mongo

2015-07-05T22:05:14.298+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
> show dbs
PersonDatabase 0.078GB
local 0.078GB
> use PersonDatabase;
switched to db PersonDatabase
> db.user.count()
3
> db.user.find()

the result is that Shirley Qian has been inserted:

{ “_id” : ObjectId(“55973f3702e8b0094967b544”), “name” : “rtsao”, “password” : “compaq”, “admin” : true, “__v” : 0 }
{ “_id” : ObjectId(“55977f4b06112d75860f9af6”), “name” : “rtsao6680”, “password” : “abcde12345”, “admin” : true, “__v” : 0 }
{ “_id” : ObjectId(“5599cc4ec1fa2c05496b5c34”), “name” : “Shirley Qian”, “password” : “12345678”, “admin” : true, “__v” : 0 }
>

Full server code

Create secure connection with Server using Certificate, ios

You are trying to communicate with a server via a client app.

Transport Layer Security (TLS), formerly Secure Sockets Layer (SSL), is the standard for encrypting and authenticating messages and identifying users and servers. Using TLS, you can be sure that the Server to which you are connected is the one intended, that no one sees the contents of your messages, and that the Server can verify that the contents they received is the one that you sent.

So given that we have an iOS client app, the server side will provide you with a .crt file.

You will need a DER-encoded X.509 public certificate in your app. The first step is to convert the .crt file to the .der file. Download the .crt file onto your desktop like so:


loadhigh.crt
….
….
Rickys-MacBook-Pro:Desktop rickytsao$ openssl x509 -in loadhigh.crt -outform der -out “trusted_cert.der”

In our example, its called loadhigh.crt

Then run

to convert the crt file to der.

Then, put the .DER encoded certificate into the bundle.

How to create a bundle

Create a folder in finder
Add the .der file to the folder
Rename the folder so that its extension is .bundle (e.g. “New folder” -> “YonoAssets.bundle”)

PS: You can at any time right click the folder and hit “Show package content” in order to add, remove or modify any of the files. Drag it into you project

<3>How to use the bundle

debugging with xCode (pt 5) – conditional debugging

Conditional

As you’re debugging your app, it may take in user input, for example, a gift name that’s a string.

Hence, code wise we want to say “if gift.name is equal to ‘xbox'”.

If you want to break whenever this string is equal to say “xbox”, you can do so using conditional debugging.

Edit the breakpoint and at the Condition textbox input the code:

The expression must evaluate to something so we simply cast it to BOOL.

Now, if you were to go back to your app and input xbox into the gift.name textfield, the runtime compiler will break to this line.

set

So now that the user have just entered “xbox”, we reach to this breakpoint. Let’s say we want to set this variable to something else instead, say “ps3”.

You simply add in an Action with the Debugger Command and insert the expression:

Again, we’re telling the debugger this is an expression and thus must evaluate to something. Since its a set command, we just cast it void.

Therefore, we’re basically saying if the user enters a string gift.name that matches “xbox”, we want to change gift.name to “ps3” instead.

debugging5_set_condition

use the code’s setter method to set gift.name to ps3 in Action >> Debugger Command‘s textfield

debugging5_action_after_condition

Now when you start the app and input “xbox”, it’ll jump to that breakpoint. While the program is paused, in your variable section, right click and select “Add Expression”. Put gift.name.

debugging5_evaluate_expression

Then, have the debugger step down 1 line (fn + F6) so that you process the line of code. In your variable section, you will see that our expression gift.name was indeed changed to “ps3”.

debugging5_changed

debugging with xCode (pt 4) – Warning and Errors

Usually, adding a lot of ‘todo’ comments is not a good idea because it will rarely be seen by others.

Hence we use #warning to throw a warning for our message when the developer compiles.

If you want it to be an error:

Playing a sound using Breakpoint

You can also put sounds in your code by first adding a break point to where you want the sound to happen. Then:

Edit Breakpoint >> Action >> Sound >> choose a sound file.

Playing a sound is a good way to know if a certain code path has been reached without having to look through the logs. You can also provide your own custom sounds in case you want to play an explosion for a particular bad crash.

To do so, just drop your sound files in this folder:

YOUR_HOME_DIRECTORY/Library/Sounds

debugging with xCode (pt 3) – Logging with break points

Logging with Breakpoints

Say at a certain line in your code, you want to log some statements. You do so by first adding a breakpoint by clicking on the vertical strip of space on the left side of your source file. Then you right click on your breakpoint and select ‘edit break point’.

debugger3_edit_brpt

For option Action, select Log Message and type in some message you would like to appear. For example, the name of the file would be a good choice. Also, the name of the method you’re in is also another great choice. You do so by using %B.

debugger3_log_msg_console

You can also log custom variables by putting variables in between %%

debugger3_logging_variables

Now, execution will stop at your breakpoint and print out your log messages

debugger3_stops_at_brpt

However, say you want the execution to keep going. You’d check the “Automatically continue…” checkbox so that you get the logging and all that, but execution continues.

debugger3_brpt_continue

Now it just uses your breakpoint to do whatever Action you intended and continues on to the next one.

debugger3_continues

Voice Logging

Next to Action, there is a + and button. Use the + button to add more actions. Select Log Message and there is a Speak Message option. Select it and it will voice your logs.

Debugger Command

Add a breakpoint on a line right beneath a variable say:

Control click or right click the breakpoint, click ‘Edit Breakpoint’, then select select “Debugger Command” from the dropdown. In the text field type the follow:

po is a debugger command that will print out the contents of an object. You can keep adding Actions >> Debugger Command and po-ing variables.

Logging with Date

Action >> Debugging command

The expr command will evaluate an expression in real time. The expression command needs to know the actual type of the returning value, so a cast is necessary. Since there is no return type for NSLog, the return type is cast to a void value. Build and run.

You should now see the following:

2012-12-20 08:57:39.942 GiftLister[1984:11603] dataStore:

Being able to add NSLog messages via. breakpoints means you no longer have to stop the program just to log important data, there’s no chance of introducing new bugs because you are not touching the code, but best of all, there’s no last minute scrambles to remove all your debug statements the night before release.

Disabling breakpoints before a release

Say you’re ready to turn in a release and you want to disable all the breakpoint logging. Simply go to your navigator and press the debug section. Then select ‘Disable breakpoints’ and that’s it. Now your code will run without all the breakpoint logging.

debugging3_disable_brpts

debugging with xCode (pt 2) – stopping at exceptions

Stopping at Exceptions

By default, when you run into an error, you’ll get a SIGART error that really does not tell us anything.

debugging2_SIGART

Currently, you cannot see the source of the compile error. To find it, you need to add an exception breakpoint to track down the source of the error.

So switch to the breakpoint navigator as shown below

debugging2_on_exception_throw

The Exception field gives you the option of activating the breakpoint in Objective-C, C++, or All. Keep the default option of All.

The Break field in the dropdown allows you to pause execution on whether an error is thrown or caught. Keep it selected on thrown. If you are actually making use of exception handling in your code, then select ‘On Catch’. For the purposes of this tutorial, leave it ‘On Throw’.

debugging2_exception_brpt

Now you’ll be able to see where the error occured.

debugging2_error_src

debugging with xCode (pt 1) – showing variables

Showing Variables

Your debugging console can be toggled by the middle button on the top right hand corner. Mainly, it shows your variables, and log outputs.

debugging_toggle_console

When you run and debug a project by throwing in breakpoints, you’ll see that your debugging console only has log outputs like so. There are no variables…you only see your output console.

debugging_no_variables

In order to have the variables showing, go to:

xCode >> Preferences

debugging_xcode_pref

and you should see and select Behaviors. Then you will see panels for Build, Testing, Running….

Under Running, select Start and on the right hand side select Variables and Console for debugger showings.

debugging_behaviors_start

Do the same for ‘Pauses’ and ‘Generate Output’.

debugging_behaviors_pause

debugging_behaviors_output

The ‘Variables & Console’ option tells the debugger to show the list of local variables as well as the console output each time a debugger session starts. If you wanted to view just the console output, you would select ‘Console View’. Likewise, if you wanted to see just the variables, you would select the ‘Variable View’.

The ‘Current Views’ option defaults to the last debugger view on your last debugger session. For example, if you closed Variables and opted to just the view the console, then just the console would open next time the debugger was started.

Now, you will see the variables appear when you debug

debugging_variables

Using UIRefreshControl in UIScrollView

How to add refresh control to a scroll view

First, set your uiviewcontroller self.view background to black.

Then create a scroll view container and set it to red.

Then have the scroll view container add a refresh control.

Finally, draw an orange square and have the container add that.

self.view
—container
——-refresh control (operates on container as background)
——-square (other UIViews added to container will be pulled down)

Once you run the app and pull down, you’ll see that the refresh control is added onto the scroll view and operates using the scrollview as the background.

refresh_control_added

Code

NSInternalInconsistencyException

If you happen to try to add the refresh control to a uiviewcontroller’s self.view, you’ll get a compiler error:

NSInternalInconsistencyException’, reason: ‘UIRefreshControl may only be managed by a UITableViewController’

You can only add it to a UITable, UICollection, and UIScrollView.

Making a successful View transition when UIRefresh is pulled

If you want to transition your view beautifully when the user pulls down on the refresh control, set your controls up so that there are 2 containers.

container1 – refresh control, other views
container2 – refresh control, other views

Then when a refresh control is pulled, you hit the event method of the ‘pull’ and make sure you animate the containers to switch. Something like this:

Thread Basics (Instantiations)

SomeClass header

SomeClass implementation

main

log output:

Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 0
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 1
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 0
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 1
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 2
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 3
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 2

As you can see

Thread A processes on object 0x7fe83960e340
Thread B processes on object 0x7fe839416a70

The access different member variables, in particular

Thread A processes on object 0x7fe83960e340’s member variable 0x7fe83960e348
Thread B processes on object 0x7fe839416a70’s member variable 0x7fe839416a78

Both threads do their work on their own respective objects because those objects were allocated on the thread’s own stack in main’s