2014-06-16 66 views
0

我是iOS開發人員的完全新手,並且正在處理我的第一個應用程序。我正在與需要用戶使用其用戶名和密碼登錄的Web服務進行交互。我想檢查並確保它們在輸入正確的用戶名和密碼之前將其保存在鑰匙串中,因此我使用憑據進行了簡單的獲取請求。我想檢查我收到的回覆,看看是否收到錯誤消息。這裏是我寫的代碼,它對Web服務執行GET請求。檢查NSURLSessionDataTask的響應值

-(BOOL)checkCredentials:(NSString *)username withPassword:(NSString *)password{ 

    NSString *requestString = @"some_web_service_url"; 
    NSURL *url = [NSURL URLWithString:requestString]; 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 

    NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0]; 
    NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential]; 

    NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration]; 
    [email protected]{@"Authorization":authString}; 

    self.session=[NSURLSession sessionWithConfiguration:sessionConfig]; 

    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

     NSLog(@"%@", jsonObject); 

    }]; 

    [dataTask resume]; 
    //I think error checking logic should go here. 
} 

我想檢查我的jsonObject的錯誤代碼,但我能做到這一點我做[dataTask resume]後?有沒有更好的方法來檢查返回碼?我相信jsonObject將返回JSON,所以我想我想檢查頭的返回值,但我不完全確定。對不起,如果這是一個簡單的問題,但我是新的,有點困惑。任何幫助將不勝感激!

回答

0

您可以通過在會話數據任務完成塊中將NSURLResponse轉換爲NSHTTPURLResponse來檢索HTTP返回碼,並檢查statusCode屬性。

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSString *user;   // Update to your user name 
    NSString *password;  // Update to your use name password 

    [self checkCredentials:user withPassword:password completion:^(BOOL authorized) { 
     if (authorized) { 
      // Save the credentials 

      dispatch_async(dispatch_get_main_queue(), ^{ 
       // Update your UI if needed. 
      }); 
     } else { 
      // Unauthorized 
      // 
      // Inform the user if needed. 
     } 
    }]; 
} 

- (void)checkCredentials:(NSString *)username 
      withPassword:(NSString *)password 
       completion:(void (^)(BOOL))authorized 
{ 
    NSString *requestString; // Update to your Web Service URL 
    NSURL *url = [NSURL URLWithString:requestString]; 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 

    NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0]; 
    NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential]; 

    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    sessionConfig.HTTPAdditionalHeaders = @{ @"Authorization" : authString }; 
    self.session = [NSURLSession sessionWithConfiguration:sessionConfig]; 

    NSURLSessionDataTask *dataTask = 
    [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     NSHTTPURLResponse *httpURLResponse = (NSHTTPURLResponse *)response; 
     NSUInteger statusCode = httpURLResponse.statusCode; 

     switch (statusCode) { 
      case 200:     // Authorized 
       authorized(YES); 
       break; 
      case 401:     // Unauthorized 
       authorized(NO); 
       break; 
      default: 
       // Unauthorized 
       // 
       // For a copmlete list of HTTP response status codes see http://www.ietf.org/rfc/rfc2616.txt 
       // also be aware that not all Web Services return the same status codes. 
       authorized(NO); 
       break; 
     } 
    }]; 

    [dataTask resume]; 
}