php - 如何使用 Xcode 执行第一个简单的 PHP api 示例

标签 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 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/

相关文章:

php - 如何在javascript中找到div的大小?

php - Joomla Extension AcySMS 需要修改源码

php - 存储客户付款详细信息 - PCI 合规性

iphone - 我的 ImageView 在 TableView 中表现不正常?

iOs 构建失败,FacebookLogin 包

iphone - 登录谷歌下载文件 - ios

ios - 异步连接中的 NSURLConnection 数据中断

PHP 解析文本 block 以进行查询

ios - 应用程序扩展键盘键在按下时被切断

ios - 有什么方法可以将参数的 NSDictionary 附加到 NSURLRequest 而不是手动制作字符串?