好的,这看起来应该很简单——我要做的就是从我的 SignIn.m(ViewController)调用我的 ServerConnect.m(NSObject)、NSURL 连接请求方法,并在 NSURL 请求完成后停止 UIActivityIndicatorView。当然,如果我在主线程上完成所有操作:
- (IBAction)forgotPassword:(id)sender {
[activityIndicator startAnimating];
connection = [[ServerConnect alloc] init];
[connection sendUserPassword:email withSecurity:securityID];
[activityIndicator stopAnimating];
}
然后,一切都将同时执行,并且活动指示器将在连接方法完成之前启动和停止......
因此,我试图将连接请求放在辅助线程上:
- (IBAction)forgotPassword:(id)sender {
[NSThread detachNewThreadSelector: @selector(requestNewPassword:) toTarget:self withObject:userEmail.text];
}
- (void) requestNewPassword:(NSString *)email
{
[self->thinkingIndicator performSelectorOnMainThread:@selector(startAnimating) withObject:nil waitUntilDone:NO];
//Make NSURL Connection to server on secondary thread
NSString *securityID = [[NSString alloc] init];
securityID = @"security";
connection = [[ServerConnect alloc] init];
[connection sendUserPassword:email withSecurity:securityID];
[self->thinkingIndicator performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
}
但是,我在这里也看不到活动指示器,这可能是由于 NSURL 请求在辅助线程上无法正常运行(即,由于某种原因,它没有像在主线程上请求时那样收集 xml 字符串) .
构建我的代码以使其工作的正确方法是什么?我很惊讶在尝试弄清楚如何让我的活动指示器在另一个文件中的方法完成执行后简单地停止时涉及了多少工作。有没有办法串联(一个接一个)而不是同时运行代码?任何帮助,将不胜感激。
更新为显示:sendUserPassword:(NSString *)withSecurity:(NSString *)
- (void)sendUserPassword:(NSString *)emailString
withSecurity:(NSString *)passCode;
{
NSLog(@"Making request for user's password");
newUser = NO;
fbUser = NO;
forgotPassword = YES;
NSString *post = [NSString stringWithFormat: @"email=%@&s=%@", emailString, passCode];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
//Construct the web service URL
NSURL *url = [NSURL URLWithString:@"http://www.someurl.php"];
//Create a request object with that URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:90];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
//Clear out the existing connection if there is one
if(connectionInProgress) {
[connectionInProgress cancel];
}
//Instantiate the object to hold all incoming data
xmlData = [[NSMutableData alloc] init];
//Create and initiate the conection - non-blocking
connectionInProgress = [[NSURLConnection alloc] initWithRequest: request
delegate:self
startImmediately:YES];
}