0

I'm am a complete newbie to iOS development and am working on my first application. I am interfacing with a web service that requires a user to login with their username and password. I want to check and make sure that they have entered the correct username and password before I save it in keychain so I'm making a simple get request with there credentials. I want to check the response I get and see if I get an error message or not. Here is the code I have written, which performs a GET request to the web service.

-(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];
    sessionConfig.HTTPAdditionalHeaders=@{@"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.
}

I want to check my jsonObject for an error code but can I do it after I do [dataTask resume]? Is there a better way to check the return code? I believe jsonObject will return json so I think I want to check the header for a return value, but I'm not fully sure. Excuse me if this is an easy question but I'm new and a bit confused. Any help would be greatly appreciated!

user2604504
  • 697
  • 2
  • 14
  • 29

1 Answers1

0

You could retrieve the HTTP return code by cast the NSURLResponse to NSHTTPURLResponse in the session data task completion block and check for the statusCode property.

- (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];
}
s3tjan
  • 1,118
  • 10
  • 13