A way to share data between apps on an iOS device

Hello everyone,

I used to think that it was impossible to passively share data between iOS apps on a given device. What I mean by that is I was under the impression that you could either share data from a server where a user is forced to login or directly by url which opens an app. I recently searched for a solution amongst the storm of developers searching for an alternate for the UDID call that Apple deprecated in iOS 5. In this post I’m going to show you the basics of how to share a unique ID that you create in 1 app and access it in another app. The way I found to accomplish this was using UIPasteboard which is essentially iOS’s way to allowing you to paste data which can be accessed by any app that knows what its looking for. You can “paste” a bunch of different types of data including dictionaries and data but in this example I’m just going to make a unique identifier, paste it to the paste board and access it in another app. Lets get started.

In the app delegate didFinishLaunchingWithOptions function of the first app:

//Create a unique id as a string
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);

//create a new pasteboard with a unique identifier
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"youruniquestring" create:YES];

[pasteboard setPersistent:YES];

//save the unique identifier string that we created earlier
[pasteboard setString:((__bridge NSString*)string)];

Here is the code to create a unique identifier using Apple’s unique ID creator which will be unique but not unique to our given device. What is important to note here is the “pasteboardWithName” function where I give it a unique identifier. This is important because it will uniquely identify this pasteboard so you know what to access in other apps and setPersistent which obviously means it will persist. We then save this code to the pasteboard with the last line(FYI I am using ARC which is why the __bridge is required).

In a separate app we can access this string with the following simple code (In the app delegate didFinishLaunchingWithOptions function of the second app):


UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"youruniquestring" create:NO];
NSLog([pasteboard string]);

Thats basically it. We created a unique identifier in one app and saved it to a pasteboard and then we accessed that string we saved in a separate app. There is a lot more that should be done here in order to use this in production but I always like to make my posts show the bare bones solution. Something to consider using this approach is that other apps have access to your data if they know what unique identifier to look for. It would probably be a very far fetched situation where someone would want to maliciously use your information or even know about it but you should keep that in mind. I hope this helps anyone looking for a tool to share information between apps and to potentially find a solution around the lack of the uniqueIdentifier function that was once supported by Apple.

-Ryan

Iphone Dev – How to communicate with server using http, json and php(or any server side language)

Hello everyone,

This is going to be a tutorial to explain how to set up a basic iphone app which communicates with a server to display data based on the server’s response. The goal of this tutorial is to help set up a base framework for a custom API and how to communicate with it in IOS. I will be using php on the server side but this can be any language you are familiar with.

Before starting on this tutorial you should be familiar with:
- Basics of http requests
- Familiarity with JSON structure and NSDictionaries
- Familiarity with UITableViews

Lets get started with the basics of what we’re gonna do.

1. Send out an http request to our server
2. Get response back and validate that its a successful return result
3. Convert the return string into an NSDictionary for us to use
4. Display the data

For our convenience we will need to download two libraries to make our lives easier. The first being a wrapper around http requests. I like using ASIHTTPRequest for simple things. You can also use Three20 but thats a big install for this purpose. We will also need a library to convert our return JSON string to a NSDictionary. For this I like to use sbJSON. Both of what you need from these are included in my sample project but visit those sites for documentation.

Lets get started

First download the sample project: Project Zip

The Server Side

In my example I’m going to be using php and I will be returning a static json array along with a status.

In the above code we can see that we are declaring the view controller to be a delegate of ASIHTTPRequestDelegate so that we can handle asynchronous loading and we are declaring a ASIHTTPRequest as a member variable.

Now lets get to the implementation file.

When doing a HTTP request you usually always want to do an asynchronous request so you do not block ui. It is also good to display some sort of activity indicator for the user so they know you are working.

We will initiate our request from the button pressed action.

- (IBAction)getDataPressed
{
    //if we are already sending a request then just do an early return
    if([myRequest_ isExecuting])
    {
        return;
    }

    if(myRequest_ != nil)
    {
        [myRequest_ release];
    }

    //Create a new url request with our url path
    myRequest_ = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:URL_PATH]];
    myRequest_.delegate = self;

    //send out the request as asynchronous
    [myRequest_ startAsynchronous];

    //Show the user that we are loading with the indicator
    activityIndicator_.hidden = NO;
}

Thats all we need to send the request. URL_PATH is defined at an earlier part in the file and is the url path to our php file. All we are doing here is creating the request, starting it asynchronously and setting ourselves to be the delegate. The last line is making our loading indicator visible to the user.

The Delegates

There are two delegate functions we are going to worry about in our example. Those are when the request finishes successfully or if it fails.

Here is our code:

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"Request finished successfully");
    NSLog([request responseString]);

    //This is all we have to do to convert our response to an NSDictionary
    NSDictionary *responseDictionary = [[request responseString] JSONValue];

    //If we have valid JSON and our success status is "YES" then we are good to go
    if(responseDictionary != nil && [[responseDictionary objectForKey:@"success"] isEqualToString:@"YES"])
    {
        dataArray_ = [[NSArray alloc]initWithArray:[responseDictionary objectForKey:@"data"]];
        [myTableView_ reloadData];
    }
    else
    {
        NSLog(@"There was a problem");
    }

    activityIndicator_.hidden = YES;
}

Here we handle when the request is successful. The line where we are initializing “responseDictionary” is where we are doing a lot of the work. We are getting the response string from the request and then using our json parser to turn that into a Dictionary. A lot of work is done for us there.

Next we need to ensure that our request was successful so we are specifically checking for “Yes” from that value. If that is yes then we set our array to the “data” value of our dictionary and reload our tableview to display our data.

Finally we set our activity indicator to hidden since we are done loading.

Or we could have a failure:

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"Request failed");
    activityIndicator_.hidden = YES;
}

Here is where you would need to handle any errors and display a proper message to the user.

And thats just about it.

Conclusion

So in conclusion we made a simple project, put a php file together that returns JSON data, read it in by using an http request from the iphone app, parsed the data and then displayed it. The sample project is really as simple as I could make it and it lacks important elements such as explicit network connection checks, memory management and other common tasks for production code. Also my php code is just echoing JSON but in reality you should do a specific return of mime type JSON

I really hope this is helpful to people who are in need of a starting path for this functionality. This type of communication is crucial for so many areas of iPhone development.

If you have any questions or comments please feel free to leave a comment on this page or email me directly:

Again you can download the project here: Project Zip

-Ryan

iPhone dev – Performing sequential UIView animations



Hello all,

This is a quick tutorial to provide a solution to sequential animations in a UIView. By sequential animations I mean having one animation complete and only after it completes begin the next animation. This is pretty easy to do with some relatively simple code.

I have included a simple xcode project to showcase this functionality which can be downloaded here: Project Download

When performing a UIView animation you are able to specify a function which will be hit when that animation completes. With this we essentially can chain the animations so when one completes it will then call a function which begins another animation. This method means that you will be adding a new function for every animation you would like to chain but for the most part this feature is mostly used to do one animation and once its completed do some work.

Lets get started

In my example I’m animating 3 imageviews where I just set the background color to red. When you press the button they will move from left to right and one at a time and if you press it again it’ll do the same thing but backwards.

my header


@interface sequentialAnimationExampleViewController : UIViewController {
	//Our images to animate
        IBOutlet UIImageView *image1;
	IBOutlet UIImageView *image2;
	IBOutlet UIImageView *image3;

	BOOL areImagesOnLeft;
}
//The button click to start the animations
- (IBAction)startAnimation;

@end

So the code that really matters is the animation blocks and we’ll just look at one in detail.

//Start of the chain
- (IBAction)startAnimation
{
	[UIView beginAnimations:@"animate" context:nil];
       //choose a random time for the animation
	[UIView setAnimationDuration:arc4random()%3];
       //This is specifying that our function "animation1Completed" will be called when the animation completes
	[UIView setAnimationDidStopSelector:@selector(animation1Completed)];
	[UIView setAnimationDelegate:self];

	 //We are just setting the x value of our imageView to be the other side of the screen
	image1.frame = CGRectMake((areImagesOnLeft ? RIGHT_SIDE_X_POSITION : LEFT_SIDE_X_POSITION),
							image1.frame.origin.y,
							 image1.frame.size.width,
							 image1.frame.size.height);

	[UIView commitAnimations];
}

This is a simple animation block with the most important things to look at are the calls to setAnimationDidStopSelector and setAnimationDelegate. We are specifying with setAnimationDidStopSelector that when this animation completes we will call the selector specified and for this to work correctly we set the delegate to self. You will see that the specified selector simply performs a very similar animation where it calls another selector on its completion.

Summary Thats basically it. This is a good tool to add some animation style to your views. My example is pretty simple and not very practical but using some animation to have a view arrange itself and then firing a function to maybe present some information might be a good use for this.

Again here is the link to download the project: Project Download

I hope this is helpful to some of you out there. If you have any questions or comments feel free to email me or leave a comment on this post.

-Ryan

Tips to get a job as an IOS developer



The world of mobile development has obviously exploded over the last few years. I choose the path of iPhone development since at the time android didn’t have any phone on the market so there wasn’t much of a choice. Since then I did hobbyist iPhone development on the side of my daily job and less than a year ago I got a job as a full time mobile developer. After getting my current position I have interviewed many applicants for IOS development jobs at my company with most of them applying for Jr level positions. I have learned a lot about getting a full time IOS development job through my experience of getting my current position along with what I feel is important with everyone who I personally interview. In this post I’ll lay out what I think is important when trying to get into this field and tips to improve your chances.

Understanding the field a little more: This field is young. Yes there are hundreds of thousands of published apps for the iPhone app store alone but thats really not saying much. I was able to pump out 7 apps by myself with no form of training. Many companies who are looking for iPhone developers don’t always know what they are looking for and many times want a do it all developer who will take an idea and art to completion. It feels to me that the market is less in the gold rush state where companies are trying to figure out the idea that wasn’t thought of yet but more so in the “me too” stage where so many people are trying to do an app like (angry birds, instagram, etc). I have experience 3 main categories of company business models in relation to IOS development . 1. Creating unique apps where the focus is to make money directly from the app through advertising or pay to purchase revenue. 2. Creating branded applications for existing companies as contract jobs or shared revenue. 3. Companies looking to add a mobile department to their existing product. In my opinion its important to at least think about which of the these you would like to seek after when searching for jobs.

People may not realize a very important fact! Although I’m sure there are huge amounts of people trying to learn IOS development and many people pumping out apps, there are not that many high quality iphone developers out there looking for jobs. This is great news for people searching for these jobs.

What employers want to see

  • I feel its obvious but the best thing to show is at least one published and non-trivial app. You don’t need an overly complex app to show your talent but it should have at least a couple of features which are well made, good looking and functional. As I interview people the more apps to show the better but its good to know the order in which the apps were made since for me the quality of my apps improved over time. Another benefit of having an app to showcase is that it can change the direction of the interview as the interviewer does not need to probe as hard with tough technical questions to understand your abilities but rather ask for explanations on what you have done.
  • If you do not have a published app then a non published app can be good to show as well but it does not look nearly as good as one which has gone through the apple approval process. Knowing how how to submit and update an app is another added talent which looks good to employers.
  • A background in software development looks good and since most will not have a background in mobile almost any software development works. This is another reason its important to have something to showcase your ability.

The technical portion and what you should know

  • Know the SDK as much as you know the language. It is important to have a good understanding of Objective C but because iPhone development is heavily reliant on the API’s provided by the IOS SDK it becomes the focus of many technical interviews. It should be noted that memory management within objective C is the one fundamental that should be known very well. Here are some examples of questions I might ask regarding general knowledge of the SDK:

  1. Explain a UITableView and what is required (delegate functions, data source functions)
  2. What is the app delegate and explain a couple of functions you should be aware of within it.
  3. Explain the difference between
     "NSString *testString = [[NSString alloc] initWithString:@"test"];" and
      "NSString *testString = [NSString stringWithString:@"test"];"
    
      Where I am looking for comments related to autorelease pool and how the memory
      is handled with each.
  • Be able to explain your apps well. It is very easy to copy and paste code for large chunks of functionality without every fully understanding it but it is also very obvious to the interviewer and looks bad. When I experience this while interviewing an applicant I loose respect for the app I am viewing and there is a sense that if a complex problem needs to be tackled that is not explained somewhere on the internet that the developer will have a hard time accomplishing it. Almost everyone begins IOS development by copying and pasting large amounts of code from forums and tutorials but to an interviewer it is a sign of an amateur developer.
  • Understand the general mobile market with at least some knowledge of the big players. Have some examples of what you like and what you use. People want to hire those who are plugged in.
  • Some other good things to have ready:

  1. knowledge on the company you are applying for.
  2. Its usually a big bonus to have some server side experience since a lot of mobile development is just a redisplay of existing web information.
  3. Know what you want to work on and if you are all about programming video games make sure you are only applying for those companies since it looks bad to a non-game company when you express that is your only desire.
  4. And other general interview preparations.

Summary

Its not a hard field to get into but it does require some work to prepare. The best tool to get the job is completed and published apps. Understand what you have done and show that you are passionate about the field. There is a lot more that can be said about this topic but I hope this can help some who are looking into this as a career.

If anyone has any other questions please feel free to email me or leave a comment on this post.

-Ryan


iPhone dev – Building a custom tableview with a background image and separate button



Hello all,

This is a simple tutorial which will explain how to create a view which will contain a UITableView with a custom background image. This will will also have a button which is not a part of the tableview. This is a simple set up but a common workflow which, when I initially started iphone development, caused me some minor headaches before I understood them. The purpose of me creating a view with a background image and separate button is to show how to set up a viewcontroller that manages a combination of a view, tableview, and other elements you would like to add.

Prerequisites: Before starting this tutorial you should have a basic understanding of viewcontrollers and uitableviews.

Lets get started: I have created a simple xcode project that you can download here which has my working example and will produce what you see below.

screen shot

Xcode can do a lot of work for you when creating a new uitableview by simply adding a new uitableviewcontroller. This is simply a viewcontroller which is specific to have its base view as a uitableview. The first thing to note is that we are starting with a uiviewcontroller. Our viewcontroller declares itself as both a UITableViewDelegate and a UITableViewDataSource. When creating a new UITableviewController it will also automatically set the uitableview’s delegate and datasource to its file’s owner.

In our case we need to add a UITableview to our viewcontroller’s view. I am using Interface builder for simplicity. Once the tableview is added we ensure that both its delegate and datasource are set to “File’s Owner” which in this case is our viewcontroller. As an alternate you can set the delegate and datasource of the tableview in code with something like the following in your init or viewdidload function of the viewcontroller:

myTableview.delegate = self;
myTableview.dataSource = self;

IB connection

Once we have this set up the tableview will be looking for the required tableview delegate and datasource functions. At a minimum we need to set up the three required datasource functions to get our example going. In my project I just put dummy text in. Again this is only to show the bare bones set up of this scenario and as a tool for understanding what is required.

The lasts steps were me simply added a UIImageView to our viewcontroller’s base view and set the background color of our tableview to be 0% alpha. I then made the tableview shorter than the full length of the view so I could add a button which does nothing in my example.

That is basically it. It is a little difficult to explain everything without becoming too verbose but I think examining the simple project I’ve added should be enough to get the concept. Its my humble opinion that understanding how to set up more complex views which includes a UITableViews is an important hurdle for new iPhone developers. This is a quick tutorial and project so if any clarification is wanted please message me.

Again you can download the sample project here.

Please let me know if you have any questions by emailing me directly or leaving a comment on this post.

-Ryan


My trip to the Outer Banks

The Outer Banks in North Carolina is a magical place for kiters as I now know. I recently went on a week long trip in late June with the sole purpose being to kiteboard. We stayed at Kitty Hawk Kiteboarding resort and we scored.

Quick overview.
6 days of potential kiting and 5 days of wind.
3 days of 30+ mph at some point in the day
3 days of kiteable wind every hour of daylight.
2 days of 20mph + every hour of daylight.
5 or 6 downwinders.

The summary of the wind was that there were more kiteable hours than your body could take each day.

I was invited to go on this trip and I did not fully understand how good Hatteras can be. Water was close to bath water and most coast line was waist to chest deep at least a couple of hundred yards out. We kited on the sound side all except for one session. The bottom is mostly hard sand with some seaweed which smells bad when it dries out. There is supposed to be oyster shells and rocks on the bottom but for the most part I didn’t encounter anything that would cut your feet.

We mostly rode out side of Kitty Hawk and did downwinders to ride in the Real “slick” area for the smoothest water I’ve felt. Even though the sound is 40ish miles wide the wind chop is very minimal. Even when it was blowing 30+ the chop only seemed just above ankle high. Still enough to get in your way to load up but you aren’t doing that much at 30mph anyway.

The launch and land is sketchy as there are very little beach areas on the sound side and lots of bushes. In once situation I had to drift launch but because the water is so shallow you can drag your kite out deep enough where its easy to do.

Beyond the amazing kiting conditions the overall atmosphere is great. Its refreshing to kite in a place that has so few regulations and 95% of all water traffic is comprised of kiters, windsurfers and jetskies for kiteboarding lessons.

I will be going there again and if you decide to visit make sure you bring as many kites as possible. One day required a 30+ kite, 20ish kite and mid teens. At one point no one in our party had a kite small enough to ride when it was blowing upper 30′s so a 7/6/5 could be used.

- Ryan

A decent ralley

iPhone dev – quick trick to get a "flash" effect



Hello all,

I’ve been using a quick little trick to get a flash effect in a lot of my iphone apps which adds a little style when switching between images or views. I generally use this when I switch between images but it works well when you’re wanting to switch something on the view but don’t want to waste much time with any form of transition.

I made an extremely simple xcode project to demonstrate this which I think may be overkill but I already had it made. Download it here

How it works: Basically all I’m doing is adding a blank white view on top of whatever is shown and performing a very fast animation on it to fade the alpha from 1.0 to 0.0 really quickly while I’m doing whatever it is I want to do (switch views/change images/update some label).

The code

- (IBAction)flashScreenPressed
{
	//make the view if we haven't already and add it as a subview
	if(flashView == nil)
	{
		flashView = [[UIView alloc]
                   initWithFrame:CGRectMake(0,
                     0,
                     self.view.frame.size.width,
                     self.view.frame.size.height)];
		flashView.backgroundColor = [UIColor whiteColor];
		[self.view addSubview:flashView];
	}

	[flashView setAlpha:1.0f];

	//flash animation code
	[UIView beginAnimations:@"flash screen" context:nil];
	[UIView setAnimationDuration:0.3f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

	[flashView setAlpha:0.0f];

	[UIView commitAnimations];

	flashLabel.text = @"Flashed";
}

This is essentially all of the code that matters. In my example I’m dynamically creating the view but if you want to be lazy you can also just add the view in Interface Builder. The animation block is just doing a .3 second animation with the cure being “Ease Out” which I think looks the best but is just opinion.

I hope this example can help developers looking for a way to provide a quick and simple flash to your app. In the project I do no form of memory management and I wouldn’t doubt that there is something I could have done to make this more efficient or a better solution.

Project Download

Good luck and if you have any questions or comments please email me or leave a comment on this post.

-Ryan


First impressions 12m Switch Nitro



Hello everyone,

This is my initial review of my new kite, the Switch Nitro 12m. I was in the market for a new larger kite as my previous was a 14 that was actually too fast(twitchy), had too little depower and performed poorly while unhooked. A very fast and forward flying big kite has its advantages but along with it comes the problem of having too little low end and with me I had to be up a couple sizes on the average at the beach for any given day. But thats not to say that when the wind is in the 20 knot range I love the characteristics I just described. I say this for so you understand what I was wanting with my new kite purchase.

My conditions: I live in an area where a decent day is in the 17 knot range and the spots I regular vary between choppy but no waves and beaches with sand bar breaks in the 2-3 foot range. Through spring the wind will get 20+ regularly but the majority of the season is 12 meter wind. I weight ~175 and am about 5’11”. I normally ride a 135 Underground Styx.

The Kite Overview: Switch is a new company based out of Hawaii and you buy the kites direct from the factories. I got the kite in a few days from Hong Kong. The Nitro is their high aspect bow kite which is claimed to be a slightly down tuned version of their C kite. You can view more on their site: Switch Nitro

The pieces

The bar: The bar has everything I wanted. The grip bar is nice and thin and has great grip. It is adjustable between two sizes by connecting the back lines between two connection points on the bar ends. The loop is nice and big and the donkey dick(which is removable) is good. What I really like is the below the bar swivel. There is also a swivel at the front line split but I didn’t have enough twists in my front lines for that to untwist itself and the below the bar manual swivel did the trick for me. The depower is a cleat system but it uses a pulley so I could easily depower my kite while flying in full power. It also comes with a bag which is a nice touch.

The Kite – Looks and set up: The kite has good looking graphics and IMO looks really good while flying. It has more of a C shape than I’m used but thats not really saying anything. It has one valve location which has two ways of unscrewing (one to open the pump hole and one to be the dump valve) It uses a very large adapter and this was the first time I pumped up a kite with a valve this big. It was so much easier than I was used to and I don’t want to go back. Also the dump valve is huge and the kite deflates almost instantly. The one pump system worked fine. The bridal has one pulley on each side and was easy to set up. The back lines are not directly connected but go through the pulley and to the front bridal but this helps the kite turn really well while depowered.

The Kite (flying) Day 1 (16knots, 1-3 foot surf): The kite felt great to me and was what I was looking for. The kite turned fast if you wanted it to but wasn’t twitchy. The bar pressure felt like medium to me and the depower throw was smooth. The power delivery was smooth but it had enough good grunt for me to get through the lulls. It was a good blend between forward flying and grunt with pop. My tricks on the first day were only hooked in front rolls and backrolls but the kite had great pop compared to my previous kite and made these a lot easier. The steering was a little mushier than my previous kite but my last kite had almost no bridal so the benefits of having a larger bridal with a pulley is worth it for me. I always knew where it was and I had the right amount of feedback while steering. The kite jumped great. It was easy to send and had great boosting potential in the mediocre wind I was in. I also did a medium power kiteloop on the way down from a jump and it pulled well and had a semi tight radius so it was easy to get around. I’ll have to do more of these in higher wind to have a better feel for it. Unhooking was great and so much better than I’m used to with other bow kites. It unhooked easily, was very smooth, Â easy to fly and never back stalled on me. I admit I only did one weak raley but that was mostly because it was the first day and I don’t like unhooking in waves. I’ll fly this kite at my flat water spot and unhook more. I never put the kite in the water but I did self launch on sand so I’d assume it relaunches easy enough.

Conclusion for now: So that is the conclusion for my first flight on my 12m Nitro. I’m very pleased with my purchase and I can’t wait to fly it more. I think this kite will have a great wind range and will be my goto kite for the rest of the summer. I will be flying as the wind comes and if I get enough feedback from this post I’d be happy to add some more info on this kite as I get some more hours on it.

Get out there and enjoy the ocean.

-Ryan


Parsing a json array in iPhone dev

Hello,

This is a quick tutorial to use a simple json parser to take a json string and parse it into an NSDictionary.

Normally you’ll be needing this when you are getting an http request back with json format. Luckily there are some good third party libraries out there to handle JSON and in this tutorial I’ll be using this one: http://stig.github.com/json-framework/

First step is to get that installed in your project by following the instructions on that site.

Now assuming the data you are going to parse is from a NSURLRequest your code might look something like this:

example json string : {“user_name”:”rooster”,”user_id”:”403039203″,”status”:”banned”}

    NSString *jsonString = [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding];

    // Create a dictionary from the JSON string
    NSDictionary *results = [jsonString JSONValue];

    //Now we can use the dictionary like normal
    NSLog( [results objectForKey:@"user_name"] );

And thats essentially it.

I will be expanding on this tutorial to include the full cycle of sending a request and getting back the json result.

-Ryan