我正在学习一些基本的php,SQL,JSON,以便我可以在我的iOS程序中使用数据库。我在应用程序中解析这些信息时遇到了麻烦。这是我的代码,但每当我运行它时,我的NSLog显示(null)。
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
//@property (nonatomic, strong) NSURLSession *session;
_session = [NSURLSession sessionWithConfiguration:config delegate:self
delegateQueue:nil];
//my test practice site url
NSString *requestString = @"http://sqlphp.site88.net/default.php";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
//@property (nonatomic) NSArray *databaseArray;
self.databaseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//shows (null) on log whenever ran
NSLog(@"%@", self.databaseArray);
}];
也可以随意跳转到网站by clicking here,但如果您不想点击,这里是JSON字符串。
[{"id":"1","name":"pippo","surname":"Mr Pippo","age":"108"},{"id":"2","name":"Paperino","surname":"Mr Paperino","age":"109"}]
有没有人知道我做错了什么,它没有显示为字符串?我几乎逐字地从Big Nerd Ranch书中复制了这个例子来练习这个,除了他们使用.json而不是.php
答案 0 :(得分:1)
使用NSError,它们通常具有解决错误所需的信息。
我将序列化行更改为:
NSArray * databaseArray = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
然后检查错误内容:
(lldb) po error
Error Domain=NSCocoaErrorDomain Code=3840
"The data couldn’t be read because it isn’t in the correct format."
(JSON text did not start with array or object
and option to allow fragments not set.)
UserInfo=0x60800046e680
所以,有了这些信息,我试图读取数据的实际内容,我得到了这个:
(lldb) po [[NSString alloc] initWithData:data encoding:4]
<html>
<head>
<title>SQL To JSON Test</title>
</head>
<body>
[{"id":"1","name":"pippo","surname":"Mr Pippo","age":"108"},{"id":"2","name":"Paperino","surname":"Mr Paperino","age":"109"}]
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
这就是问题所在! 您的网页不仅仅返回您的JSON字符串,而是包含它的HTML文件!