iPhone消耗Web服务 [英] Web service consuming from iPhone approach

查看:47
本文介绍了iPhone消耗Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何改进此代码?这个问题与 iPhone应用程序生命周期中的最后一个功能是什么有关

How can I improve this code? This question is related to What is the last function in iPhone application lifecycle

-(void)LogoutUser
{    
    int userId = [[GlobalData sharedMySingleton] getUserId];

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

    NSURL *url = [NSURL URLWithString: @"http://....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://..." 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];
    }     

}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response 
{
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{
    [webData appendData:data];  
}

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error 
{   
    [webData release];    
    [connection release];
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{   
    NSString *theXML = [[NSString alloc] 
                        initWithBytes: [webData mutableBytes] 
                        length:[webData length] 
                        encoding:NSUTF8StringEncoding];    


    [theXML release];    

    [connection release];
    [webData release];   
}

推荐答案

问题是,当您的应用程序切换到后台状态时,它不再接收任何网络更新.如果您需要网络呼叫在应用程序进入后台之前返回,那么同步呼叫可能会帮助您.

The problem is that when your application switches to the background state, it no longer receives any network updates. If you require the network call to return before the application enters the background, maybe a synchronous call will help you there.

如果您决定走这条路,我还建议您查看 ASIHTTPRequest ,因为这些类将允许您在同步调用上设置超时,而普通的 NSURLConnection 类则不允许.否则,如果服务器不响应,则可能会导致您的应用程序被iOS终止.

If you decide to go this route, I also suggest to look at ASIHTTPRequest because those classes will allow you to set a timeout on the synchronous call while the normal NSURLConnection classes won't. Otherwise you risk that your application will be terminated by the iOS if the server does not respond.

这篇关于iPhone消耗Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆