OAuth, Regex, API’s and Search Bars

Most recently, I tried my hand at pulling an API and funneling the information in a way that suited a well versed app.  I went with MakerBots Thingiverse API which is pretty unique.  On the backend, they don’t allow for a custom URL scheme, so I had to find a workaround to link a page on a website back to my app.  This was pretty neat and interesting.

(You can download the source at my Github.  You will need to create a “Constants.h” and “Constants.m” file after signing up at http://www.thingiverse.com/developers and receiving a client_ID and client_secret)

A customURL scheme is a url you can set in your xcode project to have webviews link back to your app.  For OAuth, when a user logs in, they are redirected back this custom URL.  In the case of the MakerBot API, I ping a page on my website, and have that page redirect back to my app through a simple line in html.  The url I am redirecting to is set in my custom URL scheme.

<meta http-equiv="refresh" content="0; url=thingiversesearch://oauth" />

Under Projects -> Targets -> ProjectName -> URL Types

Thingiverse  Oauth

This step solved my OAuth issues and I was able to receive an access token after a user signed in.

 Regex

When using regex, I find it great to use a resource my former teacher once showed the class called “Rubular“.  It is a ruby based site that allows for you to play around with regex expressions and find matches.  I find this helpful when doing custom url’s to find and replace strings or things that I can’t just flat out Google.

I’m using regex’s in a couple of different places in my app.  One of the most notable places where it makes a big impact on my code is when pulling image info.  When calling the API for a “thing” in the “Thingiverse”, you get an array of dictionaries that somewhat resemble the code below.

{
  "id":244,
  "name":"potatono",
  "url":"https://api.thingiverse.com/users/potatono",
  "thumbnail":"http://thingiverse-production.s3.amazonaws.com/renders/ff/46/e6/04/1f/ApocolypseBurningMan2010_thumb_medium.jpg",
  "bio":"",
  "location":"New York, NY",
  "registered":"2008-11-29T10:26:26-05:00",
  "last_active":"2012-12-31T17:29:19-05:00",
  "things":"https://api.thingiverse.com/users/potatono/things",
  "copies":"https://api.thingiverse.com/users/potatono/copies",
  "likes":"https://api.thingiverse.com/users/potatono/likes",
  "default_license":"cc",
  "email":"justin.day@makerbot.com"
}

Within that code, you get a string URL for the user’s profile image.  It is a similar line that you get for the thing’s thumbnail image.  Instead of making a second call to the API to get a list of images for a given object, I wanted to take this string and replace the end to create the URL to a bigger image myself.  This speeds up the process of having to call an API asynchronously and wait for a response before loading an image after already having obtained the object.

    NSString *thingPreviewThumbnail = thingDictionary[@"thumbnail"];
    NSString *pattern = @"(thumb_medium.jpg)";
    NSRegularExpression *regex = [NSRegularExpressionregularExpressionWithPattern:pattern options:0error:nil];
    NSString *largePreviewThumbnail = [regex stringByReplacingMatchesInString:thingPreviewThumbnail options:0 range:NSMakeRange(0, [thingPreviewThumbnail length]) withTemplate:@"display_medium.jpg"];

The above code takes the url

http://thingiverse-production.s3.amazonaws.com/renders/ff/46/e6/04/1f/ApocolypseBurningMan2010_thumb_medium.jpg

And matches for the pattern “(thumb_medium.jpg)” that is at the end of every url returned by the Thingiverse API.  In this case, I was able to directly target the section I wanted to replace.  I used Thingiverse.com to open up image urls and found that the only difference between the API call and the url I wanted was replacing the “thumb_medium.jpg” with “display_medium.jpg”.  As a result, my images went from

Thingiverse low res to Thingiverse High Res

without having to make another call to the API.

Lastly, I wanted to implement a search bar into a tableview so that users could search for specific products.  It was my first time implementing such a feature.  I used the delegate method from the search bar to make calls to the API.  By pulling the search text into the string url, you are easily able to make any call to the API for a search.  I created the custom method below to pull in from the Search

- (void) searchforThing:(NSString *)searchText withCompletion:(void(^)(NSArray * things))completionBlock{
    NSUserDefaults *defaults =[NSUserDefaultsstandardUserDefaults];
    NSString *accessToken = [defaults objectForKey:@"thingiverseAccessToken"];

    NSString *getUserInfo = [NSStringstringWithFormat:@"https://api.thingiverse.com/search/%@?access_token=%@", searchText, accessToken];

The search text that gets pulled into this custom method above comes from the Search Bar delegate method

– (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

Enhancements

There are a couple of features I would like to make better in this project app.

– Cache images for faster loading time

        – I want to implement this feature due to the size of the images I am pulling from the API.  By caching the images and also implementing a background thread for this, I should have smoother scrolling throughout my app when images are being loaded.

– Posting feature

    – I want to include a feature where the user can search for a Thingiverse object and then select that object to put into a collection.

– Better UI/UX

    Now that I have the hi-res images, I want to implement better UI to make it feel more like and app that users would want to interact with.

Diving into API’s with Objective-C

Over the course of the last week, I have been working on code challenges and trying out my own projects involving API’s.  During my time at Flatiron School, we learned how to parse out API’s into readable formats in Objective-C.  They were one of my favorite topics due to the open nature of companies and brands making their data publicly available for people to pull and experiment with.

In this case, I decided to pull information from the New York Times Best Sellers API.  the challenge I wanted to complete in this project app was to pull the information from one section of the API to be used in another section.  In this case, I wanted to pull the genre list from the API in order to then display each best seller in that genre.  I wanted to create a project where people can “browse” through genres, pick a book and learn more about it.  The current experience in the NYT app displays an ad like banner in the books section that takes you to a webview.  I chose to make my project a collection view given I have not had much experience with these before and wanted to learn something new.

The format for pulling a genre and a list of that genre are a bit different.

http://api.nytimes.com/svc/books/version/lists/names%5B.response_format%5D?api-key=your-API-key

I used the above format in order to pull all the genres in the best seller api list.  I then used those genre’s as keys, needing to use a regex to detect spacing and replace those spaces with  a “-” symbol in order for the URL to function properly. In my case, I chose to do this in the prepare for segue method in order to pass the string as property of the next view controller.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NYTGenreListTableViewController *genreListTableViewController = segue.destinationViewController;
    NSArray *indexPaths = [self.collectionViewindexPathsForSelectedItems];
    NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
    
    NYTBookGenre *genre = [self.genreArray objectAtIndex:[indexPath row]];
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpressionregularExpressionWithPattern:@"\\s"options:0error:&error];
    
    NSString *genreList = [regex stringByReplacingMatchesInString:genre.bookListNameoptions:0range:NSMakeRange(0, [genre.bookListNamelength]) withTemplate:@"-"];

    genreListTableViewController.genreKey = genreList;
}

I then use that information to call the API using that genre list with a custom API call that takes in the name of the genre  as one of the arguments.

   [self.apiClientgetGenreList:self.genreKey WithCompletion:^(NSArray *books) {
            self.genreList = books;
            NSLog(@"%@",self.genreList);
            [self.tableView reloadData];
    }];

In my custom method, I’m formatting the string in a way that calls the genre list in the appropriate section of the URL and my key in the appropriate section.

NSURL *nytBestSellerURL = [NSURLURLWithString:[NSStringstringWithFormat:@"http://api.nytimes.com/svc/books/v2/lists.json?list=%@&api-key=%@", genreList, [self.apiKeygetAPIKey]]];

You can find the full project here at Github.

Project Euler Objective-C Solutions: Question 2

A question me and a lot of my classmates are experiencing during technical interviews is one related to the Fibonacci sequence.  Question 2 on Project Euler deals with this as well and is a good resource to getting started thinking about this problem.  The Fibonacci sequence is a mathematical formula in which each number is defined by the sum of the 2 numbers before it.  The mathematical formula is as follows.

F_n = F_{n-1} + F_{n-2},\!\,

Question 2 on the Project Euler site is as follows:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

In approaching my solution, I always like to think of the method first.  What is my method going to be taking in and returning.  The question asks for a sum, so immediately, I know my method is going to returning a number.  The question also asks for the sum of numbers “in the Fibonacci sequence whose values do not exceed four million”.  We could write this method to solve for this use case, but in order to reuse the code in multiple programs, I like to take in a number, any number, into the method so I don’t have to hard code any numbers inside of my method.

- (NSNumber *)sumOfFibNumbersLessThanNumber:(NSNumber *)number

Next, I have to decide what goes into the method.  We have a number that we need to stay below, so that lets me know there is a for loop in the works.  We also know that we are returning a sum.  This means that we need a counter method to keep track of that as we run through our loop.  When determining the Fibonacci sequence, we need to remember that each number is the sum of the previous 2 numbers.  We need variables to keep track of these as well

    NSInteger sum = 0;
    NSInteger lastNumber = 0;
    NSInteger lastLastNumber = 1;
    for (NSInteger i = lastNumber; i < [number integerValue]; i++){
}

Next, I have to think about how to assign the counter values and number values.  In doing this, we know that the lastNumber needs to be assigned to the lastLastNumber and the lastLastNumber needs to become whatever i sums up to.  We get the body of the method below.

    NSInteger sum = 0;
    NSInteger lastNumber = 0;
    NSInteger lastLastNumber = 1;
    for (NSInteger i = lastNumber; i < [number integerValue]; i++){
        i = lastNumber + lastLastNumber;
        lastNumber = lastLastNumber;
        lastLastNumber = i;
}

Lastly, the problem asks for the even numbers in the sequence to be summed up.  I can then check to make sure the number is divisible by 2 and add that number to the sum, then return it.  I get the complete method below.

- (NSNumber *)sumOfFibNumbersLessThanNumber:(NSNumber *)number{
    NSInteger sum = 0;
    NSInteger lastNumber = 0;
    NSInteger lastLastNumber = 1;
        for (NSInteger i = lastNumber; i < [number integerValue]; i++) {
        i = lastNumber + lastLastNumber;
        lastNumber = lastLastNumber;
        lastLastNumber = i;
        
        if(i % 2 == 0){
            sum +=i;
        }
     }
    return @(sum);
}

You can find the working project on my Github.

Project Euler Objective-C Solutions: Question 1

Another great recommendation from my network of developers was attempting some of the questions on Project Euler.  The site is a collection of recreational programming problems meant to help developers continue learning.  It’s great for a student like myself with three months of experience in the Objective-C language.  My goal is to complete at least one question a week in order to stay focused for technical interviews.  Below I describe my solution to the first problem that is a variation of “fizzbuzz”.

The project file can be found on my Github profile.

 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

My first step in tackling this problem is thinking about how I want to set up my method.  I could have my method take in the number 1000, but I want to reuse this method for any number.  I want to write this code once and be able to reuse it in any program that would involve it.  I know two things, I want to return a number that is the sum of all the multiples of 3 & 5, and I want to input any number, in this case, the number 1000.

- (NSNumber *)sumOfMultiplesBelowNumber:(NSNumber *)number

Then I have to decide what goes into this method.  We have a number, and we have to count up all the numbers below it, determine if they are multiples of 3 or 5 or both, add the matches up, and return that as the sum.  First, I create a sum variable that will be returned at the end.  We begin this sum at 0 and I decided on an integer because it is much easier to perform math with them.  This becomes a “for” loop in which i assign an integer to count up to the given number.

NSInteger sum =0;
for (NSInteger i=0; i<[number integerValue]; i++)

Next comes the check for the multiples of 3 and 5.  I decided to do this with an “if” statement that checks if the integer i is divisible by 15 (multiples of 3 AND 5), then checking if the number is divisible by 3 only and by 5 only.

       if (i % 15 == 0) {
            sum +=i;
        }
        else if (i % 3 == 0){
            sum +=i;
        }
        else if (i % 5 == 0){
            sum +=i;
        }

Lastly, I return the sum.  The final method looks like this.

- (NSNumber *)sumOfMultiplesBelowNumber:(NSNumber *)number{
    NSInteger sum =0;
    for (NSInteger i=0; i<[number integerValue]; i++) {
        if (i % 15 == 0) {
            sum +=i;
        }
        else if (i % 3 == 0){
            sum +=i;
        }
        else if (i % 5 == 0){
            sum +=i;
        }
    }
    return @(sum);
}


This should return the sum equal to 233168






Polymorphism

One of the the repeated terms I am reading and hearing about in my studies of objective-C design patterns is “Polymorphism”.  It is something I didn’t directly learn about, but have been trying to apply to my code all along.  A developer friend of mine recommended the book recommended the book “Head First Design Patterns” to help me develop and understand more common design patterns being used in programming.  Through this book, I have come to find answers to some key questions asked to me in technical interviews.  Here is my understanding of polymorphism below.

Polymorphism is the concept of programming to a supertype or abstract class so that object s assigned to these variables don’t have to know about specific object types.  In class, we learned this as subclassing or method overriding.  Through my research, I have found the developer community torn on how best to describe this type of programming.

For example, when trying to declare many animals that make sounds inheriting from an Animal class,

Below is an explicit declaration of a dog using its sound method “bark”.  This program can not be used in any other implementation or code other than a dog barking.

Dog *dog = [[Dog alloc] init];
[dog bark];

Below, we are assigning an abstracted class of Animal that can be assigned a dog.  When the “makeSound” method is called, the Animal class knows to call the dog’s specific sound, in this case, a “bark”.

Animal *animal = dog;
[animal makeSound];


What Is Machine Learning?

Now that I have graduated from Flatiron School, the job hunt is in full swing and I am being exposed to technical interviews for the first time in my career.  It’s been a great learning experience trying to solve problems with algorithms and especially without auto-complete when using Objective-C.  I wanted to create a record of questions I am asked along the way to better prepare any future devs out there.

 

What is Machine Learning?

Machine Learning is the science of getting computers to act without being explicitly programmed.  This is how a lot of popular companies such as Netflix or Amazon are able to recommend content based on your interests and habits.  In essence, that machine is monitoring your every move and also learning your passive habits.

In addition to the online world, machine learning also refers to hardware in which you can teach a robot implicitly how to perform a task.  It can learn by observing your moves and then repeat those steps when prompted to.  Once it has an understanding of the routine, it can then carry out the functions on its own.

If you’re interested in learning more about machine learning, Coursera offers a great course for which I’ve signed up.  It would be great to get more in depth knowledge of how decisions are accessed by using algorithms.  The link is below.

https://www.coursera.org/course/ml

 

Applying CIFilters in Code

There have been many great features that iOS7 has brought to the table.  One of my favorites so far has been the use of custom filters.  This allows you to create photo apps with more right out of the box.  It also allows you to add more character to your app by manipulating backgrounds.

The first step is using Core Image objects.  By using CIContext and CIImage, we are able to manipulate the Quartz graphic context of an image.  This then lets us create the CIFilter in one line of code.  The “Gaussian Blur” effect takes in an image and a number indicating the radius of which you want to affect.  Lastly, you create a CGImageRef containing the context and filtered image.  This can now be used to create a regular UIImage and apply it to a ImageView.

-(void) filterImage:(UIImage*)image{
    //Filter
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
    
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];

    [filter setValue:inputImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumbernumberWithFloat:10.0f] forKey:@"inputRadius"];
    CIImage *resultImage = [filter valueForKey:kCIOutputImageKey];
    
    //CIgaussianBlur
    CGImageRef finalImage = [context createCGImage:resultImage fromRect:[inputImage extent]];    self.profileImageView.image = [UIImage imageWithCGImage:finalImage];
}

Resources

http://evandavis.me/blog/2013/2/13/getting-creative-with-calayer-masks

UIImageView and Masks with Objective-C

Here is a quick tutorial on how to apply an image mask with a predefined shape to your images.  This is especially useful for artful creations that may be difficult to draw programatically.

 

Using photoshop, you can create the type of mask you want to apply to a UIImageView.  Taking a simple shape, you can set out a predefined mask using black color to signify the areas you want to eventually remain exposed in your image.

 

The white space you see around the black circle will remain.  The black circle will be “transparent” when applied as a mask to your image.

circle image tutorial

 

Now, using Xcode, you can apply this to a UIImageView and create a mask using the following method.

-(void)createMaskForImage:(UIImageView *)image
{
    CALayer *mask = [CALayer layer];
    UIImage *maskImage = [UIImage imageNamed:@"circle.png"];
    mask.contents = (id)[maskImage CGImage];
    mask.frame = CGRectMake(0, 0,maskImage.size.width, maskImage.size.height);
    image.layer.mask = mask;
    image.layer.masksToBounds = YES;
}
  • Create a CALayer mask
  • Assign your photoshop image to the mask contents as a CGIImage
  • Create the frame for the mask.  In the method above, I use the mask image’s own width and height.
  • Set the UIImage layers mask property to the mask you have created in the steps above.
  • Set the mask layer bounds.

 

Once you have set this method, go back to you view did load and call it on self.

    [self createMaskForImage:self.profileImageView];

Run Xcode to see the finished product.

circle tutorial 2

Custom Camera on iOS – AVCaptureSession, AVCaptureVideoPreviewLayer tutorial

Things are going great here at Flatiron School.  We are in week 4 of the program, and I must say, this is one of the best experiences I’ve had.  When I think about how much trouble I had understanding the concept of classes and methods just 4 weeks ago, I am amazed by how I can now understand code from various sources around the internet.  It’s almost like reading english at this point.

Now that we have some of the core fundamentals down, we have been tasked with creating a custom app as our side project.  I’ve got a couple of ideas I wanted to try, but I wanted to find one that was both challenging and I knew would keep me on my toes.  I decided to do something with a custom camera.  At first, I thought, UIImagePickerController was the way to go, but I soon found out that it’s functionality is way too limited.  Essentially, the UIImagePickerController is the most basic view of a camera that Apple provides in their framework.  I wanted to control more than just the ability to take a picture.  I want to be able to tap into the phones settings and manipulate different features.  This is when I cam across AVCaptureSessions.  This is a new class provided by Apple to give developers the ability to get data from the phones camera for audio and video/photo recording capabilities.

A quick note on how custom cameras work.  Essentially, what you are looking at when you open the camera is in fact a video.  The camera opens up a video layer that takes as an input what the camera is seeing.  When you snap a picture, it is taking a screen shot of that moment, pausing the video, saving the image, then resuming the video preview playback.

Below I describe a simple way to get the preview up and running.  I found a lot of resources with elaborate code on how to build a camera out with buttons and features, but all I wanted to do to get started is get a working prototype.  Once I had that, I can worry about the hard… harder part.

create a single view application in Xcode

add a ViewController to the storyboard and create a UIViewController that it can talk to.  Make sure to link them up using the class feature in storyboard.

Then, replace the view did load with the following code, and you’ll have your working camera.  You can see it’s basically following apples guidelines, with a couple of other resources in there that helped me to get this up and running.

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

    //Capture Session
    AVCaptureSession *session = [[AVCaptureSession alloc]init];
    session.sessionPreset = AVCaptureSessionPresetPhoto;

    //Add device
    AVCaptureDevice *device =
    [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    //Input
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

    if (!input)
    {
       NSLog(@"No Input");
    }

    [session addInput:input];

    //Output
    AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
    [session addOutput:output];
    output.videoSettings =
    @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };

    //Preview Layer
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    UIView *myView = self.view;
    previewLayer.frame = myView.bounds;
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:previewLayer];

    //Start capture session
    [session startRunning];

}

Considering all of this code is being written in the viewController, I decided to refactor by creating a new Object named “CaptureSession” where I placed the above code into separate methods. I have a method for starting a new session, adding input, and adding a preview layer. This makes it super simple to come along later and change what kinds of inputs I want to add without having to refactor a bunch of different spaces.

Here is what the final code looked like in my viewController.

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

    //start Session
    CaptureSession *startSession = [[CaptureSession alloc]init];
    [startSession addInput];
    [startSession startVideoPreviewLayer];

    //Create bounds for video
    CGRect layerRect = [self.view.layer bounds];
    [startSession.previewLayer setBounds:layerRect];
    [startSession.previewLayer setPosition:CGPointMake(CGRectGetMidX(layerRect), CGRectGetMidY(layerRect))];

    //Add bounds layer to view
    [self.view.layer addSublayer:startSession.previewLayer];

    //Start running the current session with above settings
    [startSession.captureSession startRunning];
}

Breaking Ground – My Thoughts on App Stats

It’s now week 4 at Flatiron School and we are at a point where we are able to create simple apps that have object oriented programming in their inner workings.  This is a huge accomplishment, considering that 4 weeks prior, I wouldn’t have even known what an NSLog was.  That being said, more and more ideas are rushing into my head as to how apps can be organized and created.  I decided to take a look at some stats on what the popular categories are, as well as put together my own thoughts on where I think there is potential to do something great.

I found an interesting breakdown of popular categories for the year in 2013.  Quite possibly the most interesting fact is how dominating the game app category is in comparison to all other app categories.  What I find most surprising is how far down the list productivity, sports, travel, music, health and fitness, and photography app categories are down the line.  Considering there are infinite uses for the iPhone when it comes to these categories, this only means one thing.  There needs to be more innovation in these categories for people to start adopting and truly using their phones fullest potential.

appCategories2013

I’ve also taken a snapshot of where the current app rankings are in different parts of the world.  Below are US, Mexico, and Brazil app stats for February 2014.  We see the craze of flappy bird aiding other imitators in the top free apps section, but a new app in the top 10 that raked in 4 million downloads in the last day since the acquisition of WhatsApp is “Telegram”.  The main differentiator is the mix that Telegram provides between WhatsApp and Snapchat.  Allowing for secure messaging and ephemeral messaging.  This has taken off in international markets as well due to the outage that WhatsApp experienced.

US Top Free Apps February 24th, 2014

usTopAppsFeb-2014

Mexico Top Free Apps February 24th, 2014

mexicoTopFreeAppsFeb2014

As seen in the above rankings for Mexico, games dominate the free app charts as well as a photo filter app.  So even in different parts of the world, there is a rise in apps that provide some additional functionality aside from social posting.

My thoughts on all of this is that although studies suggest that people have found their perfect app and don’t continue to download even more, they are still open to improvements and enhancements to the apps they currently use and won’t mind upgrading if there is upside.  There is still much more that can be done with productivity, healthcare, news, sports, and just about every category to improve upon the current offerings in the store.

Resources

http://www.iosappstats.com/stocks/appstats.php

http://www.statista.com/statistics/270291/popular-categories-in-the-app-store/