NSURLConnection数据空回来了

时间:2014-02-18 23:05:29

标签: ios nsmutablearray nsurlconnection

我无法弄清楚为什么我的代码无效。我认为我正在做的一切正确,PHP脚本编码并显示它应该如何。有人可以查看我的代码,并建议我做错了吗?

PHP:

$link = ...succesfully connects
if ($link){
    if (isset($_REQUEST['past'])) {
        $result = mysqli_query($link, 'SELECT * FROM messages WHERE id > '.
            mysqli_real_escape_string($link, $_REQUEST['past']).
            ' ORDER BY added LIMIT 50');
        $messages = array();
        echo json_encode($messages);
    } else {
        $result = mysqli_query($link, 'SELECT * FROM messages ORDER BY timeadded LIMIT 50');
        $messages = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $messages[] = $row;
        }
        echo json_encode($messages);
    }
}

输出如下:

[{"id":"1","user":"me","message":"my first message","timeadded":"2014-02-11 12:47:55"},{"id":"2","user":"me","message":"my second message","timeadded":"2014-02-18 14:29:23"}]

这是我的ViewController代码:

h:
{
NSMutableData *responseData;
}
@property (nonatomic, strong) NSMutableArray *receivedData;


m:
@synthesize receivedData;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
NSLog(@"received response");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(@"%@", receivedData);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
receivedData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSLog(@"%@", responseData);
}

- (void)viewDidLoad
{
[super viewDidLoad];
[self getNewMessages];
}

- (void)getNewMessages {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"messages.php?past=%d", lastId] relativeToURL:[NSURL URLWithString:@"http://www.mydomain.com/"]];

responseData = [NSMutableData dataWithCapacity:0];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"GET"];

 NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
 if (conn)
 {
     receivedData = [[NSMutableArray alloc]init];
     NSLog(@"sent request to server");
 }
}

我只是在反序列化后尝试记录数组,但它在日志中显示为空。显示前两个日志,然后只显示()。我在这做错了什么?该应用程序构建和运行正常,没有错误...提前感谢!

如果我添加一个NSMutableData变量并尝试像文档中那样执行,我在didReceiveData函数中获得的数据如下所示:< 5b5d>。这是什么意思?

以下是我收到的回复:

{ status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html";
Date = "Wed, 19 Feb 2014 00:03:30 GMT";
"Keep-Alive" = "timeout=10, max=30";
Server = Apache;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
} }

答案:显然PHP脚本错了......它不喜欢isset。一旦我摆脱了这一点,我就得到了我的数据。在iOS文档之后,一切都按照它应该运行。

2 个答案:

答案 0 :(得分:1)

您没有正确使用connection:didReceiveData:您应该创建一个NSMutableData实例,并将connection:didReceiveData:中收到的数据附加到它。您应该在connectionDidFinishLoading中转换到您的数组:您尚未实现。有关示例,请查看Apple在“URL加载系统编程指南”中显示的代码。

答案 1 :(得分:1)

请参阅此文档以供参考。 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:_responseData options:kNilOptions error:nil]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
相关问题