iphone - 在 Objective-C 中获取 php 网站响应

标签 iphone objective-c ios

我有一个 php 网站,根据请求返回 YES 或 NO。 例如

www.test.com/test.php?variable=test1 会回复我 YES 和 www.test.com/test.php?variable=test2 会返回我 NO

我正在尝试将此响应放入我正在创建的 Objective-C 应用程序中,但到目前为止我还没有成功。 这是我的代码

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.test.com/test.php?variable=test1"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    NSMutableData *receivedData = [NSMutableData data];
    NSString *strData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"This is the response: %@", strData);
}else {
 }

有人可以帮我吗?还有其他方法吗?我做错了什么吗?

非常感谢各位

最佳答案

     - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
        {
            [receivedData appendData:data];
        // declre receivedData as a property of the class(in xxx.m)
            NSError *error=nil;
            NSDictionary *result=[NSJSONSerialization JSONObjectWithData:data options:
                                  NSJSONReadingMutableContainers error:&error];
            NSLog("%@", result);
    //do whatever you want...

           //the result dictionary is a JSON object and you can use it as KVC(key-value-coding) rules  
 }

如果您的应用程序以 iOS 5 为目标,只需在您创建请求的方法下将此代码用于您的 xxx.m 文件。如果您想在其他一些 iOS 版本中使用它,请查看 JSON 解析器框架。

关于iphone - 在 Objective-C 中获取 php 网站响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9650625/

相关文章:

ios - 当我尝试在 iPhone 中调用时,Swift 2.0 出错

ios - 日期格式为空

ios - 为通知创建委托(delegate)

ios - 谷歌地图 ios sdk 中心的固定标记

iphone - 遍历 iPhone 中的控件

ios - 在 iOS 中将 UIViewController 显示为警报 View

iPhone UITableView 部分

ios - iPhone上的NFC数据传输

objective-c - CGFloat:round、floor、abs 和 32/64 位精度

html - 无法阻止初始比例 = 1 的 iPhone 缩放