当我强制关闭应用程序时,如何执行方法

时间:2015-02-02 12:30:11

标签: ios objective-c iphone ios7 nsurlconnection

我想在用户强制退出应用程序时向服务器发送注销详细信息。我在" applicationWillTerminate" .method正在执行代码,但代表没有被调用,我无法注销。请问任何人请解释我如何解决这个问题?

CODE:

- (void)applicationWillTerminate:(UIApplication *)application {

    [self sendingLogoffDatatoServer];
}

- (void)sendingLogoffDatatoServer
{
    [self.connection cancel];

 //intialize new mutable Data
 NSMutableData *data = [[NSMutableData alloc]init];
 self.receiveData = data;

 //initialize URL that is Going to be Fetched
 NSURL * url = [NSURL URLWithString:@"http://service/logout"];

 //initialize a request from URL
 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

//set HTTP Method
[request setHTTPMethod:@"POST"];

//initalize a post data


NSString *postData = [NSString stringWithFormat:@"email=%@",emailString];
NSLog(@"%@",postData);
//set Request Content Type
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

//set POST Data of Request
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

//initialize a Connection from Request
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
self.connection = conn;

//strat the Connection
[conn start];
NSLog(@"Connection Started");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  [self.receiveData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
 if(error)
{
    UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"TITLE" message:@"Couldn't Connect to the Server. Please Try Again."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorAlert show];
 }
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  NSLog(@"Posted");
}

1 个答案:

答案 0 :(得分:0)

在此行之后尝试此操作

//initialize a Connection from Request
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
self.connection = conn;

//strat the Connection
[conn start];
NSLog(@"Connection Started");

[NSThread sleepForTimeInterval:2.0];  // call the sleeper time interval


-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
 NSLog(@"Posted");
 [[NSThread mainThread] exit];   // call the thread break or use exit (0)
}