这是我从演示 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;
}
谢谢
最佳答案
你的connection:didReceiveData:方法在哪里?它应该将接收到的数据附加到 webData 中。
关于php - 如何使用 Xcode 执行第一个简单的 PHP api 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15625562/