如何取消Web服务调用 - IOS

时间:2011-07-22 07:10:02

标签: iphone objective-c web-services nsurlconnection

我的iPhone应用程序中有用户身份验证。用户登录的方式是应用程序将用户名/密码发送到Web服务以供用户检查。我现在遇到的问题是我不知道如何设置'超时'(30秒)并停止从网络服务请求数据?

NSString *soapMsg = 
    [NSString stringWithFormat:
     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>...", username, password
     ];

    NSURL *url = [NSURL URLWithString: @"http://...Service.asmx"];      

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];    
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];

    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];   
    [req addValue:@"http://.../LoginUser" forHTTPHeaderField:@"SOAPAction"];    
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];   
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];

    if (conn) 
    {
        webData = [[NSMutableData data] retain];
    }    

3 个答案:

答案 0 :(得分:4)

[req setTimeoutInterval:urInterval];
setTimeoutInterval:
     

设置接收器的超时间隔,以秒为单位。

     

- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval

     

<强>参数

     

timeoutInterval

The timeout interval, in seconds. If during a connection attempt
     

请求保持空闲的时间超过超时间隔   请求被认为已超时。默认超时间隔   是60秒。

答案 1 :(得分:0)

您可以使用NSURLConnection的取消方法

/*! 
    @method cancel
    @abstract Cancels an asynchronous load of a URL.
    @discussion Once this method is called, the asynchronous load is
    stopped, and the NSURLConnectionDelegate associated with the
    receiver will no longer receive any asynchronous callbacks for
    this NSURLConnection.
*/
- (void)cancel;

答案 2 :(得分:0)

也许ASIHTTP可能对您有所帮助?

另外,如果我理解正确,那么堆栈溢出大多为similar issue