这是我从演示 iOS 应用程序调用的第一个 API。我只是想让我在php中写的简单句子回到标签。
但是,当我在应用程序中获取它时,字典结果为空。这是如何运作的?***已更正,以下代码有效,但不是很安全
PHP 文件:
index.php hosted on localhost using XAMPP (http://localhost/tutorials/index.php) if I echo "hi"; it shows on the page so the server is working.
<?php
if(function_exists($_GET['fe'])) {
$_GET['fe']();
}
function getLabel(){
$response['name']="Hello first API ever";
echo json_encode($response);
}
现在在 Xcode 我有:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//Main parse
//Web data
NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@"%@",data);
NSString*label=[data valueForKey:@"name"];
_answer.text=label;
}
-(void)getData{
NSURL*url=[NSURL URLWithString:@"http://localhost/tutorials/index.php?fe=getLabel"];
NSURLRequest*request=[NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
}
//Clear response
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength:0];
}
//Append data
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//Main parse
//Web data
NSDictionary*data=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(@"%@",data);
NSString*label=[data valueForKey:@"name"];
_answer.text=label;
}
谢谢