2013-06-14 4 views
0

좋아,이 작업은 매우 간단해야합니다. 원하는 작업은 내 SignIn에서 내 ServerConnect.m (NSObject), NSURL 연결 요청 메서드를 호출하기 만하면됩니다. .m (ViewController)를 호출하고 NSURL 요청이 완료된 후 UIActivityIndicatorView를 중지합니다. 물론, 내가 주 스레드에서 모든 것을 할 경우 :XCode : 다른 파일에서 메서드를 실행 한 후 활동 표시기 애니메이션을 중지하십시오.

따라서 ...

- (IBAction)forgotPassword:(id)sender {  
    [activityIndicator startAnimating]; 
    connection = [[ServerConnect alloc] init]; 
    [connection sendUserPassword:email withSecurity:securityID]; 
    [activityIndicator stopAnimating]; 
} 

그런 다음, 모든 후 동시에 실행되며, 작동 표시등이 시작하고 연결 방법이 완료되기 전에 중지됩니다, 일부 (즉, 내가 NSURL 요청이 보조 스레드에서 제대로 작동하지 인해 어떤있을 수 있습니다, 하나 여기에 작동 표시등이 표시되지 않는,

- (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]; 
} 

그러나 : 나는 보조 스레드에 연결 요청을 배치하려고 시도 이유, 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]; 
} 
+0

당신은'sendUserPassword의 구현 보여줄 수 :. withSecurity을'방법 – Alladinian

+0

는 GCD를 사용하기보다는 직접 스레드를 관리하는 시도 해 봤나?또는 완료 블록에서 애니메이션을 중지하는 비동기 연결입니까? – Abizern

+0

나는 이것을하지 않았습니까? @Abizern, 이것이 어떻게 수행 될지에 대한 예제 또는 참조를 제공 할 수 있습니까? – JRoss

답변

0

(see Multithreading for iOS) 내 문제를 해결할 수 있습니다. 이는 눈살을 찌푸리게 될 어떤 이유 :.. 다른 코드의 한 부분에서 업데이트를 보낼 수

"쉬운 방법 중 하나는 애플의 내장 NSNotification 시스템

그것은 당신은 NSNotificationCenter 싱글을 매우 간단 얻을 것 ([NSNotificationCenter defaultCenter]를 통해) :

1) 보내려는 업데이트가있는 경우 postNotificationName을 호출합니다. 사용자가 작성한 고유 한 문자열 만 지정하면됩니다 (예 : "com.razeware.imagegrabber.imageupdated ") 및 객체 (예 : 이미지 다운로드를 방금 완료 한 ImageInfo)

2.)이 업데이트가 언제 발생하는지 알아 보려면 addObserver : selector : name : object를 호출합니다. 우리의 경우 ImageListViewController는 이것이 일어날 때 알기를 원할 것입니다. 그래서 적절한 테이블 뷰 셀을 다시로드 할 수 있습니다. 이것을 넣을 좋은 장소는 viewDidLoad입니다.

3. 뷰가 언로드되면 removeObserver : name : object를 호출해야합니다. 그렇지 않으면, 통지 시스템이 언로드 된 뷰 (또는 할당되지 않은 오브젝트가 나 빠지거나)에있는 메소드를 호출하려고 시도 할 수 있습니다. 이것은 나쁜 일입니다. "

0

한 가지 제안은 다음과 같이 시도 : 나는 NSNotification 시스템을 통합 결국

- (IBAction)forgotPassword:(id)sender 
{ 
    [self->thinkingIndicator startAnimating]; 
    [NSThread detachNewThreadSelector: @selector(requestNewPassword:) toTarget:self withObject:userEmail.text]; 
} 

- (void) requestNewPassword:(NSString *)email 
{ 
    //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]; 
} 
+0

불행히도, 같은 결과 ... : \ 다른 아이디어, @ Midhun? – JRoss

0

이것을 끝내면 블록을 사용합니다. 나는 비슷한 일 right here했다

// Turn indicator on 

// Setup the request 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]]; 
[request setTimeoutInterval: 90.0]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:postData]; 
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad; 

[NSURLConnection sendAsynchronousRequest:request 
       queue:[NSOperationQueue currentQueue] 
       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
       // Its has finished but sort out the result (test for data and HTTP 200 i.e. not 404) 
       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
       if (data != nil && error == nil && [httpResponse statusCode] == 200) 
       { 

       // Connection finished a gooden 
       // Do whatever you like with data 
       // Stop indicator 

       } 
       else 
       { 
       // There was an error, alert the user 
       // Do whatever you like with data 
       // Stop indicator 

       } 

      }];