当我下载每小时预测以及条件图标时,我对iOS和开发天气应用程序相当新。我已经能够使用NSURL Connection实现UICollection。但是,我遇到有关NSURL会话的速度/性能问题。以下是两个问题:
1)下载和呈现下载的图标的速度非常慢(并且图像非常小)。此下载过程可能需要5-10秒。
2)当我按下按钮重置集合时,所有数据都会重置,但现有图像会保留,直到下载新图像为止。这可能需要5-10秒。
这是我的代码:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.hours.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"ConditionsCell";
ConditionsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.conditionsTime.text = [self.hours objectAtIndex:indexPath.row];
cell.conditionsTemp.text = [NSString stringWithFormat:@"%@°", [self.hoursTemp objectAtIndex:indexPath.row]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:[self.hoursIcons objectAtIndex:indexPath.row]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
UIImage * serverImage = [UIImage imageWithData: data];
cell.conditionsImage.image = serverImage;
}];
[dataTask resume];
return cell;
}
这是按钮的IBAction并重新加载CollectionView:
- (IBAction)selectDay:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0)
{
self.todayOrTomorrow = @"today";
}
else if (sender.selectedSegmentIndex == 1)
{
self.todayOrTomorrow = @"tomorrow";
}
self.hours = [self hours];
self.hoursIcons = [self hoursIcons];
self.hoursTemp = [self hoursTemp];
[_collectionViewHours reloadData];
}
答案 0 :(得分:1)
您正在后台下载数据,但没有在主线程上更新UI,请尝试以下模式,它将帮助您
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"ConditionsCell";
ConditionsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.conditionsTime.text = [self.hours objectAtIndex:indexPath.row];
cell.conditionsTemp.text = [NSString stringWithFormat:@"%@°", [self.hoursTemp objectAtIndex:indexPath.row]];
cell.conditionsImage.image = [UIImage imageNamed:""];//reseting image
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString: [self.hoursIcons objectAtIndex:indexPath.row]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
@autoreleasepool {//autorelease pool for memory release
if (!error) {
//UIImage * serverImage = [UIImage imageWithData: data];//comment this extra variable and can increase memory overhead.
dispatch_async(dispatch_get_main_queue(), ^{
cell.conditionsImage.image = [UIImage imageWithData: data];//update UI
});
}}//autorelease pool
}];
[dataTask resume];
return cell;
}
它肯定会帮助你完成第一部分。
感谢。