开发者

Web service consuming from iPhone approach

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜