我有一个 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/