0

当视图控制器发生变化时,我需要从现有的 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
4

1 回答 1

0

您的 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"];
    }];
}];
于 2013-09-15T14:32:23.740 回答