从从 php 检索的值中设置 UILabel 文本


Set UILabel text from values retrieved from php

我需要从现有的 php 文件中自动获取一个变量,以便在视图控制器更改时替换标签的文本。视图控制器的更改发生在按下按钮时(如果这是相关的?我已经在我们的主机上制作了数据库,变量已经到位。

1) I need to know how to adress the automation problem
2) I need to know how to get the variable from the php file

你的PHP应该以Objective-C程序容易使用的格式返回变量中的内容,例如JSON。所以,例如,

<?php
// retrieve the value of $result variable any way you want. I'm going to just set the literal
$result = "Hello World!"; 
// now convert to an array
$result_array = array("result" => $result);
// return the json_encoded rendition
echo json_encode($result_array);
?>

这将最终返回如下所示的结果:

{"result":"Hello World!"}

现在,您的Objective-C代码可以使用该JSON,例如:

NSURL *url = [NSURL URLWithString:@"..."]; // put your URL in here
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    // make sure there wasn't a connection error
    if (connectionError) {
        NSLog(@"%s: sendAsynchronousRequest error: %@", __FUNCTION__, connectionError);
        return;
    }
    // parse the JSON data
    NSError *error = nil;
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    // make sure there wasn't a JSON parsing error
    if (error) {
        NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
        return;
    }
    // now grab the "result" value from the dictionary we parsed from the JSON
    // make sure to do all UI stuff on the main queue, though
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        self.label.text = jsonDictionary[@"result"];
    }];
}];