views:

88

answers:

2

hi everyone, i wrote a gps-application for the iphone and it all works fine but now i want to send the latitude and longitude to a server over the internet using the most simple way... I have a url from the server in which there are parameters for latitude and longitude. Also i want the lat. and long. to be sent every 90 seconds or so. How exactly is all of this done? Any help is much appreciated, thanks in advance!

+3  A: 
NSURL *cgiUrl = [NSURL URLWithString:@"http://yoursite.com/yourscript?yourargs=1"];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:cgiUrl];

/* leave the rest out if just issuing a GET */
NSString *postBody = @"yourpostbodyargs=1";

NSString *contentType = @"application/x-www-form-urlencoded; charset=utf-8";
int contentLength = [postBody length];

[postRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
[postRequest addValue:[NSString stringWithFormat:@"%d",contentLength] forHTTPHeaderField:@"Content-Length"];
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
/* until here - the line below issues the request */

NSURLConnection *conn = [NSURLConnection connectionWithRequest:postRequest delegate:self];

handle errors and received data using:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // data has the full response
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    contentLength = [response expectedContentLength];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)newdata
{
    [data appendData:newdata];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}

you need some variables set up, such as data, contentLength etc. But this is the general outline for http interaction.

You may want to put all handling stuff in a separate handler class, I changed the delegate to self so this is more self-contained.

As for timing, use an NSTimer to invoke posting the data every 90 seconds:

[NSTimer scheduledTimerWithTimeInterval:90 target:self selector:@selector(xmitCoords) userInfo:nil repeats:YES];
mvds
+1  A: 

I think the above answer has the right idea - but try using ASIHTTPRequest. A great library, and it abstracts all that messy HTTP code out of your program.

Also one other thing to note - GPS coordinates every 90 seconds is going to burn down your battery very fast - are you just doing this for testing?

phooze
No but the iphone's goning to plugged into a powersource constantly and i also built in the option to turn the transfer completely off or extend the period between transfers up to one hour
Christoph v
Makes sense - just be careful if you're doing any sort of "fleet tracking" and using Google Maps API/MapKit - it's against their terms of service.Also, is this question answered sufficiently?
phooze