我需要从现有的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
答案 0 :(得分: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"];
}];
}];