0

I have three different UITextField in a "ViewController" and I would like to change these values for the ones I have in my MySQL Database. (I would like to show: followers, pictures and posts).

I know MySQL and PHP, but I'm stuck at the moment because I don't know how to do it.

First I would like to say that at the beginning, the user is going to log in using a form PHP+MySQL, maybe I have to store the username in some "var" and user later for populate those three labels with the information.

The problem is that this is my first app, and I don't know how to do it, that's why I need your help. How can I put the values from MySQL to XCode, and also, how can I store the username in a "global var" in order to use it later?

If you know any better process, please tell me, because I really want to know how to do this, because later I will have to show the profile image, profile name, etc, etc.

Edited with code:

ViewController.m

That's my login button, I will add the "load" inside the login.php file.

- (IBAction)loginClicked:(id)sender {
    @try {

        if([[_txtUsername text] isEqualToString:@""] || [[_txtPassword text] isEqualToString:@""] ) {
            [self alertStatus:@"Porfavor, introduce el usuario y contraseña" :@"Error"];
        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[_txtUsername text],[_txtPassword text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://example.com/login.php"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[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];

            [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            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);

                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
                NSLog(@"%ld",(long)success);
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    //[self alertStatus:@"Welcome." :@"Datos correctos"];
                    [self performSegueWithIdentifier:@"Main" sender:self];

                } else {

                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertStatus:error_msg :@"Datos incorrectos"];
                }

            } else {
                if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Ha ocurrido un problema inesperado" :@"Error"];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Error." :@"Error"];
    }
}

Thanks in advance.

WirajPS
  • 97
  • 1
  • 9

1 Answers1

0

What you want to do is send an AJAX (Asynchronous JavaScript and XML) request to your server to request the information you want to display.

Server

Set up an API to deliver the information. This API will process urls like https://example.com/api.php?action=userinfo&userid=1, grab the desired information from the MySQL database send them back to the user. To send the data back, you just print the information as JSON encoded string so the client can easily process it. You could actually encode it differently as well but this is the easiest and most common way to do it.

$action = $_GET['action'];
switch ($action) {
    case "userinfo":
        $userid = $_GET['userid'];
        $data = // Grab data from sql database based on the userid
        die(json_encode(array("message" => "Getting user information succeeded.", "status" => "success", "data" => $data), JSON_PRETTY_PRINT));
    default:
        die(json_encode(array("message" => "API request failed.", "status" => "error")), JSON_PRETTY_PRINT)
}

Client

On the client side, your iOS application, you can use NSURLConnection to grab this information. Have a look at these posts on how to send a http request to your server and get the response:

The only thing left is converting the response from JSON string format to an xcode NSDictionary to further process in your application.

NSString *jsonString = // web server response;
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) { 
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
    if (jsonError == nil) {
        // Set your text fields here.
    }
}
Community
  • 1
  • 1
Ke Vin
  • 2,004
  • 1
  • 18
  • 28
  • Much appreciated Ke Vin, I'm going to read your posts in order to solve this problem. As I'm very newbie with the xcode (just started 3 weeks ago) I'm going to update the first message with my xcode project because I'm not sure where to put the code or where to call NSDictionary (never use it before). Thanks again for your help Ke Vin, it's my first app and I really need thing very clear and short. – WirajPS Sep 12 '14 at 09:56
  • You could use https://github.com/julian-weinert/JWRESTClient along with https://github.com/julian-weinert/JWURLConnection as easy wrappers to JSON APIs. – Julian F. Weinert Sep 12 '14 at 10:00
  • Also I would like to know if I have to call that code (API) at the begining when the user writes the username, because later it's not gona happen and I need that in order to make the SQL Query. How can I do that? – WirajPS Sep 12 '14 at 10:00
  • Hi Julian, I'm confused at the moment because that file is so big. That's what I need to show the result of a MySQL Query into a UITextField? Because it's so large...! Thanks again. – WirajPS Sep 12 '14 at 10:03
  • You should read up on the topics I brought up before you start coding. If the user registers (that's what you meant right?) and you want to do it via the api you have to add a method for that and react on an url like *example.com/api.php?action=register*. You should send a POST request instead of a GET one though. But like I said, read up on these topics, this is very basic and there are a lot of good tutorials and blogs out there that can help you. Most of your question will be clarified. – Ke Vin Sep 12 '14 at 10:12
  • Thanks again Ke Vin, I'm followeing your guides and code in order to make it. I'm going to post my first code in the first message to check is everything is ok. Thanks again. – WirajPS Sep 13 '14 at 06:31