Public API – iOS CREATE Fence

The following code demonstrates how to create the data required to create a fence through the API.

For the code below, the Customer API Key and Zone Id are stored within a singleton Configuration object.

/*
 *  Send the URL request with the required method for processing.
 */
+ (void)sendCreateFence: (NSString *)name withLat: (double)lat andLon: (double)lon
{
    NSString  *apiCreateRequest = @"https://api.bluedotinnovation.com/1/fences";
     
    NSURLSession *session = [ NSURLSession sharedSession ];
 
    //  Ensure that the command string is escaped properly for use in HTTP
    NSString  *escapedQuery = [ apiCreateRequest stringByAddingPercentEncodingWithAllowedCharacters: [ NSCharacterSet URLQueryAllowedCharacterSet ] ];
     
    NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL: [ NSURL URLWithString: escapedQuery ] ];
    [ request setHTTPMethod: @"POST" ];
    [ request setHTTPBody: [ self createFence: name withLat: lat andLon: lon ] ];
 
    //  The content-type for the request must be explicitly provided when using JSON in the body
    [ request setValue: @"application/json" forHTTPHeaderField: @"Content-Type" ];
     
    //  Create an asynchronous connection; this will utilise App Transport Security (ATS) to an https connection is required
    NSURLSessionDataTask *task = [ session dataTaskWithRequest: request completionHandler: ^( NSData *data, NSURLResponse *response, NSError *error )
    {
        if ( error == nil )
        {
            if ( [ data length ] > 0 )
            {
                //  Retrieve the response as a dictionary containing the JSON
                NSDictionary *jsonResponse = [ NSJSONSerialization JSONObjectWithData: data options: 0 error: nil ];
                 
                //  Ensure that the response code from the Public API is for a successful transaction
                if ( ( ( NSString *)jsonResponse[ @"messageCode" ] ).intValue != 200 )
                {
                    NSLog( @"Create fence error:\n%@", jsonResponse );
                }
            }
        }
        else
        {
            NSLog( @"Create fence error: %@", error );
        }
    } ];
    
    //  Start the URL session task
    [ task resume ];
}
 
/*
 *  Create the JSON for a create fence request given a latitude and longitude position; the radius will be set to 30m.
 *  Create each of the NSDictionaries and NSArrays that will be translated into the correct JSON format.
 */
+ (NSData *)createFence: (NSString *)name withLat: (double)lat andLon: (double)lon
{
    //  Create a centre point with the latitude and longitude passed in
    NSDictionary  *center = [ NSDictionary dictionaryWithObjectsAndKeys:
                               [ NSString stringWithFormat: @"%lf", lat ], @"latitude",
                               [ NSString stringWithFormat: @"%lf", lon ], @"longitude",
                               nil ];
 
    //  Create a coloured circle with a 30m radius, giving it the name passed in
    NSDictionary  *circle = [ NSDictionary dictionaryWithObjectsAndKeys:
                                 name, @"name",
                                 @"#000fff", @"color",
                                 @(30), @"radius",
                                 center, @"center",
                                 nil ];
    
    //  The circles are created within an array
    NSArray  *circles = [ [ NSArray alloc ] initWithObjects: circle, nil ];
    
    //  The circles array is contained within the fences group
    NSDictionary  *fences = [ NSDictionary dictionaryWithObjectsAndKeys:
                                 circles, @"circles",
                                 nil ];
    
    /*
     *  The Zone Id for the fence to be created in is stored within a singleton configuration object for this example.
     */
    NSDictionary  *zone = [ NSDictionary dictionaryWithObjectsAndKeys:
                               Configuration.instance.userZoneId, @"zoneId",
                               fences, @"fences",
                               nil ];
     
    //  Create the content group with the zone data
    NSDictionary  *content = [ NSDictionary dictionaryWithObjectsAndKeys:
                                 zone, @"zone",
                                 nil ];
    
    /*
     *  Create the security group.
     *  The Customer API Key is stored within a singleton configuration object for this example.
     */
    NSDictionary  *security = [ NSDictionary dictionaryWithObjectsAndKeys:
                                   Configuration.instance.apiKey, @"apiKey",
                                   Configuration.instance.customerApiKey, @"customerApiKey",
                                   nil ];
    
    /*
     *  Create the request group with the data created above.
     */
    NSDictionary  *requestData = [ NSDictionary dictionaryWithObjectsAndKeys:
                                        security, @"security",
                                        content, @"content",
                                        nil ];
 
    //  Serialise the data above into a JSON data object   
    NSError  *error;
    NSData  *jsonData = [ NSJSONSerialization dataWithJSONObject: requestData
                                                         options: NSJSONWritingPrettyPrinted
                                                           error: &error ];
     
    return( jsonData );
}
Created by Bluedot DevOps on March 5, 2018

Start the discussion