Azad Azad - 4 months ago 17
iOS Question

Sending location updates to the server via iPhone app on every 5 minute while app is in background

I want to build a function where the current location of the user will be send to the server in every 5 minutes.Doesn't really sound like something Apple is going to like.
This will be an in-house app though (and the users know their location are used), are rules less strict for this? Anyone any experience on this?

Thanks in advance!

Answer

Seems like a very straight forward case.

Enabled background location service requirement in your PLIST file, put a disclaimer in your app description stating continuous use of GPS in background will drastically drain battery, then have your code upload your GPS location every 5 minute.

It'll work even in background :)

I have an app on the app store that records the user's route live as the user drives around, though it doesn't send to the server, it does track the user's own location constantly and when the user is done, they can stop the GPS tracking.

Some Code Suggestions

Tracking user's location isn't a one line thing but I can suggest a learning route, which isn't too overwhelming.

First of all, there are two parts to your problem:

a) Tracking user's location b) Sending the user's GPS coordinate to the server

Tracking User's Location

Tracking the user's location can be done in two ways. You can either use CLLocationManager to track the user's location or if you want the quick and dirty method, you can use the MKMapView's delegate method:

// --------------------------------------------------------------
// Example .m files implementation
// --------------------------------------------------------------
-(void)viewDidLoad
{
    ...
    myMapView.delegate = self;
    ...
}

// --------------------------------------------------------------
// this MapView delegate method gets called every time your 
// user location is updated, you can send your GPS location
// to your sever here
// --------------------------------------------------------------
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    // pseudo-code
    double latitude = userLocation.coordinate.latitude;
    double longitude = userLocation.coordinate.longitude;

    // you need to implement this method yourself
    [self sendGPSToServerWithLatitude:latitude AndLongitude:longitude];
}

// sends the GPS coordinate to your server
-(void)sendGPSToServerWithLatitude:(double)paramLatitude AndLongitude:(double)paramLongitude
{
    // ------------------------------------------------------
    // There are other libraries you can use like
    // AFNetworking, but when I last tested AFNetworking
    // a few weeks ago, I had issues with it sending
    // email addresses or multiple word POST values
    // ------------------------------------------------------


    // here I am using ASIHttpRequest library and it's ASIFormDataRequest.h class
    // to make a POST value to a server. You need to build the server web service
    // part to receive the latitude and longitude
    NSURL *url = [NSURL urlWithString:@"http://www.youserver.com/api"];

    __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSNumber numberWithDouble:paramLatitude] forKey:@"latitude"];
    [request setPostValue:[NSNumber numberWithDouble:paramLongitude] forKey:@"longitude"];
    [request setPostValue:userNameString forKey:@"username"];

    [request setCompletionBlock:^{
        NSDictionary *data = [request responseString];

        NSLog(@"Server response = %@", data);
    }];

    [request setFailedBlock:^{
        NSLog(@"Server error: %@", [[request error] localizedDescription]);
    }];

    [request startAsynchronous];
}

PHP Server-side Code

// --------------------------------------------------------------
// This is an example server implementation using PHP and Symfony
// web framework.
//
// You don't have to use PHP and Symfony, you can use .NET C# too
// or any other server languages you like to build the web service
// --------------------------------------------------------------

class DefaultController
{
    ...

    // -------------------------------------
    // expects and latitude and longitude
    // coordinate pair from the client
    // either using POST or GET
    // -------------------------------------
    public function recordGPSLocationAction()
    {
        // checks to see if the user accessing the
        // web service is authorized to do so
        if($this->authorize())
        {
            return new Response('Not authorized');
        }
        else // assume user is authorized from this point on
        {
            // check to see if user has passed in latitude and longitude
            if(!isset($_REQUEST['latitude']) || !isset($_REQUEST['longitude']
            || !isset($_REQUEST['username'])
            {
                throw $this->createNotFoundException('Username, Latitude or Longitude was not received');
            }
            else
            {
                // write your latitude and longitude for the specified username to database here

                ....

                return new Response('User GPS location saved');
            }
        }
    }
}