NSURLConnection并初始化数据对象

时间:2014-06-04 03:24:42

标签: objective-c json object nsurlconnection

我有一个iOS应用程序,它从远程PHP文件中提取JSON并在表格中显示该数据。当我使用我的数据库/ JSON文件时,一段代码不会运行。但是,当我使用教程的数据库(http://codewithchris.com/iphone-app-connect-to-mysql-database/)时,它工作正常。我已经使用了教程中的确切代码,JSON看起来完全相同,并且PHP工作正常。我该如何解决这个问题?

目标-C

#import "HomeModel.h"
#import "Location.h"

@interface HomeModel()
{
    NSMutableData *_downloadedData;
}
@end

@implementation HomeModel

- (void)downloadItems
{
    // Download the json file
    NSURL *jsonFileUrl = [NSURL URLWithString:@"192.168.0.4/service.php"];
    NSLog(@"Donwload the JSON file");

    // Create the request
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
    NSLog(@"Create the request");

    // Create the NSURLConnection
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    NSLog(@"Create the NSURLConnection");
}

#pragma mark NSURLConnectionDataProtocol Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse      *)response
{
    NSLog(@"Inititalize the data object");

    // Initialize the data object
    _downloadedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the newly downloaded data
    [_downloadedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations
    NSMutableArray *_locations = [[NSMutableArray alloc] init];

    // Parse the JSON that came in
    NSError *error;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData  options:NSJSONReadingAllowFragments error:&error];

    // Loop through Json objects, create question objects and add them to our questions array
    for (int i = 0; i < jsonArray.count; i++)
    {
        NSDictionary *jsonElement = jsonArray[i];

        // Create a new location object and set its props to JsonElement properties
        Location *newLocation = [[Location alloc] init];
        newLocation.name = jsonElement[@"Name"];
        newLocation.address = jsonElement[@"Address"];
        newLocation.latitude = jsonElement[@"Latitude"];
        newLocation.longitude = jsonElement[@"Longitude"];

        // Add this question to the locations array
        [_locations addObject:newLocation];
    }

    // Ready to notify delegate that data is ready and pass back items
    if (self.delegate)
     {
       [self.delegate itemsDownloaded:_locations];
    }
}

@end

编辑:进一步分析后,- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response之前的所有内容都有效。当接下来这段代码时,没有任何反应。 `

0 个答案:

没有答案