【发布时间】:2015-12-28 01:33:11
【问题描述】:
我是在 iOS 上使用数据库领域的初学者。但是我可以找到一种连接到 MySQL 数据库、下载和解析 json 提要的方法。现在在 iOS 9 中,我不能再使用 NSURLConnection,这就是为什么我必须用 NSURLSession 替换它。我在这里看到了很多教程,例如this。到目前为止,我无法更换它。因为时间紧迫,我不能浪费更多的时间来做这件事。有人可以帮我换吗?
我的代码看起来完全像这样:
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:@"http://myhost.ch/test.php"];
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 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.idS = jsonElement[@"idStatistic"];
newLocation.temp = jsonElement[@"temp"];
newLocation.hum = jsonElement[@"hum"];
newLocation.date_time = jsonElement[@"date_time"];
// 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];
}
}
【问题讨论】:
标签: mysql objective-c json database parsing