如何使用Xcode执行第一个简单的PHP api示例
这是我在iOS演示应用程序中调用的第一个API。我只想把我在php中写的简单句子放回一个标签 但是,当我在应用程序中获得字典结果时,它是空的。这是怎么回事? ***更正,下面的代码可以工作,但不是很安全 PHP文件:如何使用Xcode执行第一个简单的PHP api示例,php,ios,nsurlconnection,nsjsonserialization,Php,Ios,Nsurlconnection,Nsjsonserialization,这是我在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 workin
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);
}
谢谢您的连接在哪里:didReceiveData:method?它应该将接收到的数据附加到webData。是否也实现了connection:didReceiveResponse:和connection:didReceiveData:?此外,错误参数不应传递nil。这是有原因的。所以使用它,然后检查data==nil,如果是,则记录错误。URL正确吗?如何将函数添加到url?因此是否出现错误?我不知道你的URL是否正确,但如果正确,错误应该是“坏URL”。我不知道你所说的“向url添加函数”是什么意思是的,然后我向php添加了if并更改了url,结果成功了,但是我不认为这是最好的方法?如果我想发送一个参数呢?如何在URL中做到这一点?只是将其与其他方法一起添加
-(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;
}