从iPhone方法消费的Web服务

时间:2011-04-09 09:06:15

标签: iphone objective-c web-services soap

如何改进此代码? 此问题与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];   
}

1 个答案:

答案 0 :(得分:0)

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

如果您决定采用这种方式,我还建议您查看ASIHTTPRequest,因为这些类允许您在同步调用上设置超时,而普通NSURLConnection类则不会。否则,如果服务器没有响应,您可能会被iOS终止。