Question

I am trying to use simple Login using JSON and Webservice. The web service is blocked using Gateway username and password. What code is needed to include to pass the username and password to the gateway? Why is this happening? I get a Response code as 0 . Also if someone could provide a good tutorial to learn about web services and JSON in iOS. Thanks in advance.

Here is my code. Code is written in UIButton

            NSString *post = [NSString stringWithFormat:@"&Email=%@&Password=%@",
                [self.emailTextField text], [self.passwordTextfield text]];
            NSLog(@"PostData: %@",post);

            NSURL *url = [NSURL URLWithString:@"http:/Gateway/api/json/reply/ZympayAuthenticateCustomer"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData = [NSURLConnection sendSynchronousRequest:request 
                                                    returningResponse:&response error:&error];
            NSLog(@"Response code: %ld", (long)[response statusCode]);
            if ([response statusCode] >= 200 && [response statusCode] < 300) {
                NSString *responseData = [[NSString alloc]initWithData:urlData 
                                                               encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);
                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData
                                                          options:NSJSONReadingMutableContainers
                                                          error:&error];
                NSLog(@"Data: %@",jsonData);
                NSLog(@"Success: %ld",(long)success);

                if (success == 1) {
                    NSLog(@"Login SUCCESS");
                }
                else {                                
                    NSString *error_msg = (NSString *) jsonData[@"error_message"];
                   [self alertStatus:error_msg :@"Sign in Failed!" :0];
                }
            } 
            else {
                //if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
            }
        }
    }  
    @catch (NSException * e) 
    {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }
    if (success)
    {
        NSLog(@"THIS IS SUCCESS");
        // [self performSegueWithIdentifier:@"login_success" sender:self];
    }
}
Was it helpful?

Solution

Try this

NSURL *URL = [NSURL URLWithString:@"http://www.site.com/test_json_link/?username='USERNAME'&password='PASSWORD'"];

Now, to prevent my web server from redirecting to the login page. I created a middleware to handle the above url. My custom middleware has this in it:

if request.path != '/accounts/login/' and request.user.is_anonymous():
     url = request.path.split('/')[1]
     if url == 'test_json':
         username = request.GET['username']
         password = request.GET['password']
         user = authenticate(username = username, password = password)
         if user is not None:
             if user.is_active:
                 login(request, user)

OTHER TIPS

There are a number of issues in your code.

The single one which makes your approach quite likely to fail, is that you use NSURLConnection convenient class method sendSynchronousRequest:: If the request requires authentication, the credentials must be passed in the URL.

See also: sendSynchronousRequest:returningResponse:error:

Additionally, you have no way to cancel the request and take appropriate actions when the request is redirected.

So, the first big change in your approach would be to use NSURLConnections delegate approach, or possibly use NSURLSession and NSURLSessionTask. There are quite a few solutions on SO which should give you a jump start to implement your own.

The recommended solution however, is to use a third party library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top