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!
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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];
回答2:
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?