【问题标题】:iPhone SDK: How to send data to a server over the internet?iPhone SDK:如何通过互联网将数据发送到服务器?
【发布时间】:2023-03-21 16:07:01
【问题描述】:

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

【问题讨论】:

    标签: iphone nsurlconnection


    【解决方案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];
    

    使用以下方法处理错误和接收到的数据:

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

    【讨论】:

    • 是不是必须先创建一个网站?
    【解决方案2】:

    我认为上述答案的想法是正确的——但请尝试使用ASIHTTPRequest。一个很棒的库,它可以从你的程序中抽象出所有混乱的 HTTP 代码。

    还有一件事需要注意 - 每 90 秒的 GPS 坐标会很快耗尽你的电池 - 你这样做只是为了测试吗?

    【讨论】:

    • 不,但 iphone 会不断插入电源,我还内置了完全关闭传输或将传输间隔延长至一小时的选项
    • 有道理 - 如果您正在执行任何类型的“车队跟踪”并使用 Google Maps API/MapKit,请小心 - 这违反了他们的服务条款。另外,这个问题的答案是否充分?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多