【发布时间】:2015-12-26 14:25:27
【问题描述】:
我想从我的主机下载一些项目, 但现在我收到警告: 'connectionWithRequest:delegate:'在 iOS9.0 中已弃用 - 使用 NSURLSession'
我到处搜索,但不幸的是我找不到任何解决方案。
你能帮帮我吗?
我的代码如下所示:
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:@"http://myhost.com/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];
}
}
【问题讨论】:
-
错误提示您应该使用
NSURLSession。你是说你真的找不到任何描述如何使用NSURLSession的东西?!?这令人惊讶,因为它是一个涵盖广泛的主题。 -
是的,但我不知道如何用NSURLSession替换它。你能帮我用 NSURLSession 替换我的代码吗?我是这个领域的新手,非常感谢你。
标签: ios objective-c json ios9 nsurlsession