当我下载时时预报和条件图标时,我对iOS和开发天气应用程序相当陌生。我已经能够用NSURL连接实现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];
}发布于 2014-09-29 22:26:37
您正在后台下载数据,但不更新主线程上的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;
}它肯定会对你的第一部分有所帮助。
谢谢。
https://stackoverflow.com/questions/26109142
复制相似问题