Вопрос

In my app I need to include a button action to update the value of a MySQL field in a remote server. When the user taps on the button, the app should add 1 to a field value.

The MySQL value is shown in a UILabel.

I have written the PHP file to make the update to the database.

In my viewController I am getting the id field to be passed to the PHP file.

This is the button action that performs the value update:

- (IBAction)votarAction:(id)sender {
    //URL definition where php file is hosted
    int categoriaID = [[detalleDescription objectForKey:@"idEmpresa"] intValue];

    NSString *string = [NSString stringWithFormat:@"%d", categoriaID];
    NSLog(@"ID EMPRESA %@",string);
    NSMutableString *ms = [[NSMutableString alloc] initWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
    [ms appendString:string];
    // URL request
    NSLog(@"URL = %@",ms);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
    //URL connection to the internet
    [[NSURLConnection alloc]initWithRequest:request delegate:self];

}

What I need is that after tapping on the button, and the field value is updated, to show the new value at the UILabel. Which is the best way to do this?

Это было полезно?

Решение

This is a good way do it:

dispatch_queue_t backgroundQueue = dispatch_queue_create("com.domai.queue", 0);

dispatch_async(backgroundQueue, ^{

    int categoriaID = [[detalleDescription objectForKey:@"idEmpresa"] intValue];

    NSString *string = [NSString stringWithFormat:@"%d", categoriaID];
    NSLog(@"ID EMPRESA %@",string);
    NSMutableString *ms = [[NSMutableString alloc] 
                                      initWithString:@"http://url.php?id="];
    [ms appendString:string];

    // URL request
    NSLog(@"URL = %@",ms);
    NSURLRequest *request = 
                      [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];

    //URL connection to the internet
    NSData *responseData = [[NSURLConnection alloc]
                                    initWithRequest:request delegate:self];
    NSLog(@"responseData= %@",responseData);//["34"]

    //Parse JSON
    NSMutableDictionary  * json = [NSJSONSerialization 
                               JSONObjectWithData:responseData 
                                          options: NSJSONReadingMutableContainers 
                                            error: &error];

    NSString *labelValue = (NSString*) [json objectAtIndex:0];

    dispatch_async(dispatch_get_main_queue(), ^{
        //update your UIlabel dataLabel
        dataLabel.text = labelValue;
    });    
});

You should make the request and return the JSON in a background thread, then update the UILabel in the main queue.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top