2010-07-18 87 views
1

我为iPhone写了一个gps应用程序,它一切正常,但现在我想通过互联网使用最简单的方式将经纬度发送到服务器...我有一个来自服务器的URL是纬度和经度的参数。我也想要拉特。和长。每90秒左右发送一次。这一切究竟如何?任何帮助非常感谢,提前感谢!使用iPhone SDK:如何通过互联网向服务器发送数据?

回答

4
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]; 

处理错误和接收到的数据:

- (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 
{ 
} 

你需要一些变量的设置,如数据,CONTENTLENGTH等。但是,这是HTTP交互的大致轮廓。

您可能希望将所有处理的东西放在单独的处理程序类中,我将该代理程序更改为self,因此这是更具自包含性的。

至于时机,使用NSTimer调用发布数据每90秒:

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

这是否意味着我必须先创建一个网站? – user3768495 2015-07-17 22:29:47

1

我觉得上面的回答有正确的想法 - 但尝试使用ASIHTTPRequest。一个伟大的图书馆,它从你的程序中抽象出所有那些混乱的HTTP代码。

另外还有一点需要注意 - 每90秒GPS坐标将非常快地烧毁电池 - 您是否只是在做这个测试?

+0

不,但iPhone的磨练不断插入电源,我也建立在选项完全关闭转移或延长传输之间的时间长达一小时 – 2010-07-19 17:38:04

+0

有道理 - 只要小心,如果你做任何形式的“车队跟踪”和使用Google Maps API/MapKit - 违反了他们的服务条款。 此外,这个问题是否足够回答? – makdad 2010-07-19 23:55:26

相关问题