【发布时间】:2023-03-21 16:07:01
【问题描述】:
我为 iphone 编写了一个 gps 应用程序,一切正常,但现在我想使用最简单的方式通过互联网将纬度和经度发送到服务器......我有一个来自服务器的 url有纬度和经度的参数。我也想要纬度。和长。每 90 秒左右发送一次。这一切究竟是如何完成的?非常感谢任何帮助,在此先感谢!
【问题讨论】:
我为 iphone 编写了一个 gps 应用程序,一切正常,但现在我想使用最简单的方式通过互联网将纬度和经度发送到服务器......我有一个来自服务器的 url有纬度和经度的参数。我也想要纬度。和长。每 90 秒左右发送一次。这一切究竟是如何完成的?非常感谢任何帮助,在此先感谢!
【问题讨论】:
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
{
}
您需要设置一些变量,例如数据、内容长度等。但这是 http 交互的一般大纲。
您可能希望将所有处理内容放在一个单独的处理程序类中,我将委托更改为self,因此它更加独立。
至于计时,使用NSTimer 调用每 90 秒发布一次数据:
[NSTimer scheduledTimerWithTimeInterval:90 target:self selector:@selector(xmitCoords) userInfo:nil repeats:YES];
【讨论】:
我认为上述答案的想法是正确的——但请尝试使用ASIHTTPRequest。一个很棒的库,它可以从你的程序中抽象出所有混乱的 HTTP 代码。
还有一件事需要注意 - 每 90 秒的 GPS 坐标会很快耗尽你的电池 - 你这样做只是为了测试吗?
【讨论】: