iPhone SDK:如何通过互联网将数据发送到服务器? [英] iPhone SDK: How to send data to a server over the internet?
问题描述
我为iphone编写了一个gps应用程序,并且一切正常,但是现在我想使用最简单的方法通过互联网将纬度和经度发送到服务器上...我在服务器上有一个网址,有用于纬度和经度的参数.我也要拉特.而且很长.每90秒左右发送一次.这一切到底是怎么完成的?非常感谢您的任何帮助,谢谢!!
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!
推荐答案
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
{
}
您需要设置一些变量,例如data,contentLength等.但这是http交互的一般概述.
you need some variables set up, such as data, contentLength etc. But this is the general outline for http interaction.
您可能希望将所有处理内容放在单独的处理程序类中,我将委托更改为self
,因此这更加独立.
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.
关于计时,请使用NSTimer
调用每90秒发布一次数据:
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];
这篇关于iPhone SDK:如何通过互联网将数据发送到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!