Search code examples
iosobjective-cxcode4

Searching an API in Xcode


I am developing an iPhone application that is using an API to find recipes from http://www.recipepuppy.com/about/api/.

There are three parameters that must be put into return results. There are i, q, and p, Where i are the ingredients, q in a normal search query and p is the page number. I am able to specifically add these parameters and then load the results into a table view in Xcode.

I also want to implement a search that allows the users to search for recipes based on whatever they feel like and return the results. Could someone point me in the correct direction on how to do this. I know I will have to take what ever the user inputs and place it into a string but how do I implement that string into the parameters of the URL?


Solution

  • To answer your question:

    I know I will have to take what ever the user inputs and place it into a string but how do I implement that string into the parameters of the URL?

    You can use the stringWithFormat method of NSString. For example:

    NSString *ingredients = @"ingredients";
    NSString *query = @"soups";
    NSString *page = @"1";
    
    NSString *url = [NSString stringWithFormat:@"http://www.recipepuppy.com/api/?i=%@&q=%@&p=%@",ingredients,query,page];
    

    Before using this URL, it's recommended that you URL encode it.

    NSString *encodedURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    Now that you have your URL, just start a connection to the web (NSURLConnection, AFNetworking, the choice is yours), parse the data returned, and load that into an array to display in the table view.