我认为您的 PHP 代码中缺少引号。您可能打算:
<?php
$idwlctxt = "hello";
echo $idwlctxt;
?>
此外,作为良好的防御性编程问题,您可能希望使用dataWithContentsOfURL
为您检测错误的再现:
NSString *urlString = @"https://WEBSITE/test.php?";
NSError *error = nil;
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:kNilOptions error:&error];
if (error)
NSLog(@"%s: dataWithContentsOfURL error: %@", __FUNCTION__, error);
else
{
NSString *result = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(@"%s: result = %@", __FUNCTION__, result);
// if you were updating a label with an `IBOutlet` called `resultLabel`, you'd do something like:
self.resultLabel.text = result;
}
一旦你得到上面的代码,下一个逻辑增强就是使用 JSON(这是一种更好的将数据从 PHP 传递到 Objective-C 程序的技术)。PHP 代码如下所示:
<?php
$idwlctxt = "hello";
// As your PHP gets more complicated, you might want to handle errors and report
// them back to the client with a non-zero `status`, so I always return a status code.
// Clearly, this is so trivial that no error handling is needed, but it's a good
// habit to write your PHP with an eye on more extensive error handling in the future.
$response = array("status" => 0, "idwlctxt" => $idwlctxt);
echo json_encode($response);
// this should generate a response, something like:
//
// {"status":0, "idwlctxt":"hello"}
?>
接下来,让我们解析这个 JSON 响应,并异步执行,这样我们就不会阻塞主队列:
NSString *urlString = @"https://WEBSITE/test.php?";
NSURL *url = [NSURL URLWithString:urlString];
// rather than using `dataWithContentsOfURL`, let's use NSURLConnection to do an asynchronous request,
// so that the request doesn't block the main queue
// first, make the NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// now, let's send that request asynchronously
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// first, check to see if there was an error with sendAsynchronousRequest
if (connectionError) {
NSLog(@"%s: sendAsynchronousRequest error: %@", __FUNCTION__, connectionError);
return;
}
// you generally don't do this conversion of the data to a string,
// but it's useful to use this technique if you are diagnosing problems with your JSON
//
// NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%s: raw JSON = %@", __FUNCTION__, jsonString);
// now, let's parse the JSON
NSError *parseError = nil;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parseError];
if (parseError) {
NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, parseError);
return;
}
// now, let's extract our data from the JSON
NSNumber *status = results[@"status"];
NSString *idwlctxt = results[@"idwlctxt"];
NSLog(@"%s: status = %@; idwlctxt = %@", __FUNCTION__, status, idwlctxt);
self.resultLabel.text = idwlctxt;
}];
还有其他可能的增强功能,但我担心我可能已经向你扔了太多东西,所以我会在这里停下来。