2016-02-14 46 views
0

我正在使用Objective-C。我們知道AFNetworking正在另一個線程中工作,但如果我想在互聯網請求後做些什麼呢。在AFNetworking的同一線程中執行某些操作

例如:

- (BOOL)checkPassword 
{ 

    self.loginPermit = NO; 

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; 
    NSDictionary *parameters = @{@"username": self.username, @"password": self.password}; 

    [manager POST:self.URL parameters:parameters progress:nil 
      success:^(NSURLSessionDataTask *task, id responseObject) 
    { 
     NSDictionary *dict = (NSDictionary *)responseObject; 
     if ([[dict objectForKey:@"msg"] isEqualToString:@"00001"]){ 
      self.loginPermit = YES 
     } 
     else { 
      self.loginPermit = NO; 
     } 
    } failure:^(NSURLSessionDataTask *task, NSError *error) { 
     NSLog(@"Error: %@", error); 
    }]; 

    return self.loginPermit; 
} 

但它不會返回每一次。如何在互聯網請求後返回該值。

+0

您需要在完成塊中做任何事情 - 在這裏設置'loginPermit'屬性。可能最好的方法是將一個塊傳遞給checkPassword方法而不是讓checkPassword返回一個Bool – Paulw11

回答

0

您應該爲此使用塊。

[self checkPassword:^(BOOL loginPermit) { 
    if(loginPermit){ 
     // do your stuff 
    } 
}]; 


- (void)checkPassword:(void(^)(BOOL loginPermit))completion 
{ 

BOOL loginPermit = NO; 

// show indicator 

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; 
NSDictionary *parameters = @{@"username": self.username, @"password": self.password}; 

[manager POST:self.URL parameters:parameters progress:nil 
     success:^(NSURLSessionDataTask *task, id responseObject) 
    { 
     //hide indicator 

    NSDictionary *dict = (NSDictionary *)responseObject; 
    if ([[dict objectForKey:@"msg"] isEqualToString:@"00001"]){ 
     loginPermit = YES; 
    } 
    else { 
     loginPermit = NO; 
    } 

    completion (loginPermit); 

    } failure:^(NSURLSessionDataTask *task, NSError *error) { 
    NSLog(@"Error: %@", error); 

    //hide indicator 
    completion (loginPermit); 
    }]; 
} 
+0

我應該用__block聲明loginPermit BOOL loginPermit; –

+0

是的,你可以做到。 – iOSEnthusiatic

相關問題