iPhone应用程序生命周期中的最后一个功能是什么

111*_*110 2 iphone objective-c ipad ios

在我的应用程序将要关闭之前,我必须从Web服务注销用户.而且我找不到应用程序死之前调用的最后一个函数?

-(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];   
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ker 6

您需要两个地方来触发您的注销代码,这两个地方都在UIApplicationDelegate协议参考文档中有详细说明.

对于iOS 4之前的设备(以及涵盖其他情况),您应该使用:

- (void)applicationWillTerminate:(UIApplication *)application
Run Code Online (Sandbox Code Playgroud)

正如Apple所说:

对于不支持后台执行或链接到iOS 3.x或更早版本的应用程序,当用户退出应用程序时,始终会调用此方法.对于支持后台执行的应用程序,当用户退出应用程序时通常不会调用此方法,因为在这种情况下应用程序只是移动到后台.但是,可以在应用程序在后台运行(未挂起)并且系统由于某种原因需要终止它的情况下调用此方法.

但是,你需要使用......

- (void)applicationDidEnterBackground:(UIApplication *)application
Run Code Online (Sandbox Code Playgroud)

...在iOS 4+设备上,(再次来自Apple文档):

在iOS 4.0及更高版本中,当用户退出支持后台执行的应用程序时,将调用此方法而不是applicationWillTerminate:方法

也就是说,无论上述情况如何,当您的应用程序处于后台运行时,您很可能希望注销Web服务,并在"唤醒"时重新登录.有关更多详细信息,请参阅上述applicationDidEnterBackground:方法和applicationWillEnterForeground:方法文档.