当应用程序通过HTTP Post与服务器通信时,如何显示AlertView?我当前的代码无法正常工作。
基本上,一个AlertView要求确认一些事情。如果确认,则会发生以下代码:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{//this is for when the person clicks OK
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"OK"])
{
//do alert
UIAlertView *waitAlert = [[UIAlertView alloc] initWithTitle:@"Communicating with Server..."
message:nil
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[waitAlert addSubview:loading];
[loading startAnimating];
[waitAlert show];
//communicate with Server
RetailTransaction *retailTransaction = [[RetailTransaction alloc]init];
ServerConnection *serverConnection = [[ServerConnection alloc]init];
NSData *serverResponse = [serverConnection postData:[retailTransaction xmlToXml:
note.text:
pin.text:
total.text]];
NSString *serverResponseString = [[NSString alloc] initWithData:serverResponse
encoding:NSUTF8StringEncoding];
NSLog(@"Server Responded with: %@", serverResponseString);
这个方法有更多的代码,但这会得到基本的东西。 waitAlert
甚至在应用程序与服务器通信之后才会出现,此时它只会瞬间出现。有谁知道为什么会这样?它应该在与服务器通信之前出现。提前致谢。
答案 0 :(得分:1)
将此部分移动到另一个函数并在后台线程中运行该函数。
//communicate with Server
RetailTransaction *retailTransaction = [[RetailTransaction alloc]init];
ServerConnection *serverConnection = [[ServerConnection alloc]init];
NSData *serverResponse = [serverConnection postData:[retailTransaction xmlToXml:
note.text:
pin.text:
total.text]];
NSString *serverResponseString = [[NSString alloc] initWithData:serverResponse
encoding:NSUTF8StringEncoding];
NSLog(@"Server Responded with: %@", serverResponseString);
....
警告视图在调用之前未显示的原因是主线程被挂起。
答案 1 :(得分:0)
-(void)sendMessage{
NSString *url = @"http://www.your-server.com";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setDelegate:self];
[request startAsynchronous];
[alertView show];
}
-(void)requestFinished:(ASIHTTPRequest *)request{
[alertView hide];
}
-(void)requestFailed:(ASIHTTPRequest *)request{
NSLog(@"%@", [[request error] description]);
}
在这种情况下,您可以从启动警报的位置调用[self sendMessage],但我对其进行了简化。关键是异步执行请求。
此示例不执行POST,但也可以使用ASIHTTPRequest。