为什么我的loginAuth
卡在了while循环中?
我将connectionFinishLoading
声明为
@interface LoginViewController : UIViewController {
BOOL connectionFinishLoading;
}
@property (nonatomic, assign) BOOL connectionFinishLoading;
@implementation LoginViewController
@synthesize connectionFinishLoading;
-(BOOL)loginAuth {
NSString *requestString = [NSString stringWithFormat:@"http:myURL?id=%@&format=JSON", userName.text];
NSMutableURLRequest *requestURL = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestString]];
loginConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
[SVProgressHUD showInView:self.view status:@"Logging in"];
while (!connectionFinishLoading) {
NSLog(@"waiting..");
}
// code to executed after connection did finish loading.
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
connectionFinishLoading = YES;
}
答案 0 :(得分:3)
因为您阻止了运行循环并且没有数据包通过网络发送,因此连接永远不会完成。
答案 1 :(得分:0)
尝试添加:
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
// A delegate method called by the NSURLConnection if the connection fails.
// Production quality code would either display or log the actual error.
{
#pragma unused(conn)
#pragma unused(error)
assert(conn == self.connection);
NSLog(@"didFailWithError %@", error);
connectionFinishLoading = YES;
}
但是创建这样的循环是非常糟糕的做法
答案 2 :(得分:0)
正如JustSid所说,运行循环被阻止。我建议删除“while”循环和BOOL connectionDidFinishLoading属性,然后将要执行的代码移动到connectionDidFinishLoading方法中。您仍应以某种方式处理连接失败块。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// code to executed after connection did finish loading.
}