如何在iOS应用中完成HTTP帖子

时间:2012-02-28 22:15:36

标签: http post nsurlconnection

好的,所以我有代码发布到我的php网站,但我想要一种方法来确保数据到达那里。有没有办法让submision挂起它超时或服务器响应说提交被接受?

这是我到目前为止的代码:

      //Create String
    NSString *var1 =@"waitTime=";
    NSString *var2 =@"&cover=";
    NSString *wait = [var1 stringByAppendingString:waitTime.text];
    NSString *co = [var2 stringByAppendingString:cover.text];


    NSMutableURLRequest *request = 
    [[NSMutableURLRequest alloc] initWithURL:
     [NSURL URLWithString:@"http://mysite.net/index.php"]];

    [request setHTTPMethod:@"POST"];

    NSString *postString = [wait stringByAppendingString:co];

    [request setValue:[NSString 
                       stringWithFormat:@"%d", [postString length]] 
   forHTTPHeaderField:@"Content-length"];

    [request setHTTPBody:[postString 
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

2 个答案:

答案 0 :(得分:1)

您可以将状态代码设为explained in this link

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
   NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
   int code = [httpResponse statusCode];
}

状态代码已定义at this link

201

在POST命令之后,这表示成功,但响应行的文本部分表示应该知道新创建的文档的URI。

<强>更新

如果连接超时,你应该在连接时看到这个:didFailWithError:delegate方法被调用。

答案 1 :(得分:0)

看看documentation for NSURLConnection。简而言之,您要做的是实现NSURLConnectionDelegate协议的一些委托方法;各种消息将发送给代表,告诉您负载的进展情况。