暑假第四周——天气预报仿写

iOS学习

前言

作为最后一个项目,暑期培训也迎来了尾声。这个项目中初次尝试了网络申请,在iOS学习中迈出重要一步。


简介

该项目主要有搜索,预览,添加,详情几个功能组成。其中学习了引入第三方库以使用SVG图片,进行简单的网络申请实现模糊搜索等。

首页

该页面使用数组,储存城市的id以便进行网络申请。

简单的网络申请

网络申请分成五步

  • 创建请求地址
  • 创建请求类
  • 创建会话
  • 根据会话创建任务
  • 启动任务
objectivec 复制代码
-(void)creatURL
{
		//创建请求地址
        NSString *urlString1 = [NSString stringWithFormat:@"https://devapi.qweather.com/v7/weather/3d?location=%@&key=你的key",self.array_city[self.flag]];
        urlString1 = [urlString1 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url1 = [NSURL URLWithString:urlString1];
        
        //创建请求类
        NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
        
        NSURLSessionConfiguration *config1 = [NSURLSessionConfiguration defaultSessionConfiguration];
        //创建会话
        NSURLSession *session1 = [NSURLSession sessionWithConfiguration:config1 delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        //根据会话创建任务
        NSURLSessionTask *task1 = [session1 dataTaskWithRequest:request1];
        self.datatask01 = task1;
        //启动任务
        [task1 resume];
        
    
}
objectivec 复制代码
//接受服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    NSLog(@"didReceiveResponse");
    if(dataTask == self.datatask01) {
        if (self.data1 == nil) {
            self.data1 = [[NSMutableData alloc] init];
        } else {
            self.data1.length = 0;
        }
    }
   //允许数据接受
    completionHandler(NSURLSessionResponseAllow);
}

//接收到数据,该方法会被调用多次

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");

    if (dataTask == self.datatask01) {
        [self.data1 appendData:data];
    }
}

//数据请求完成或者请求出现错误调用的方法
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError");
    // 在 URLSession:task:didCompleteWithError: 方法中
    if (task == self.datatask01) {
        if (error == nil) {
            NSMutableDictionary *dictBianYi = [NSJSONSerialization JSONObjectWithData:self.data1 options:kNilOptions error:nil];

            NSMutableArray *arrValue = [[NSMutableArray alloc] init];
            
            arrValue = dictBianYi[@"daily"];
            
            [self.arrWeNeed addObjectsFromArray:arrValue];
            
    
        } else {
            NSLog(@"errol = %@",error);
        }
    }
    
    if (task == self.datatask02) {
        if (error == nil) {

            NSMutableDictionary *dictBianYi = [NSJSONSerialization JSONObjectWithData:self.data2 options:kNilOptions error:nil];
            NSMutableDictionary *arrValue = [[NSMutableDictionary alloc] init];
            
            arrValue = dictBianYi[@"now"];

            NSString *str = arrValue[@"temp"];
            NSString *str_time = arrValue[@"obsTime"];
            
            
            [self.array_temp addObject:str];
            

            [self.array_time addObject:str_time];

        } else {
            NSLog(@"errol = %@",error);
        }
        NSLog(@"2");
    }
    
    if (task == self.datatask03) {
        if (error == nil) {
            NSMutableDictionary *dictBianYi = [NSJSONSerialization JSONObjectWithData:self.data3 options:kNilOptions error:nil];

        NSMutableArray *arrValue = [[NSMutableArray alloc] init];

        arrValue = dictBianYi[@"location"];
        
            [self.array_cityName addObject:arrValue[0][@"name"] ];
            
            
        [self.dictWeNeed_city addObjectsFromArray:arrValue];


        } else {
            NSLog(@"errol = %@",error);
        }
        NSLog(@"3");
    }
    
    self.number ++;
    if (self.number % 3 == 0) {
        //返回主线程调用
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{//该代码块在返回主线程时调用,
                [self.tableView reloadData];
            }] ;
        
    }

}

这就完成了简单的网络请求,网络请求得到的是json数据,是数组和字典的嵌套,如果看不懂可以在专门的网站中转化格式数据格式转换网站

如果我们想要一次创建多个网络申请,只需在最后更新数据的时候,增加一个判断,当到我们需要的时候在更新数据即可。

搜索功能

效果:

该模糊搜索功能,通过在网络请求时,将搜索文本改为文本框的内容实现。

objectivec 复制代码
NSString *urlString = [NSString stringWithFormat:@"https://geoapi.qweather.com/v2/city/lookup?location=%@&key=3feab86d156d457b916ff85326e8593c",self.searchBar.text];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];

添加功能

该功能主要使用了属性传值和协议传值的方法。点击搜索的单元格,通过属性传值进入详情页面。而协议传值则是使用协议,将需要添加的城市代码添加到城市数组中,并通过协议的方法传给主界面。

此处的判重采用将首页的城市数组传入该页面,判断该城市代码是否添加过。

objectivec 复制代码
-(void) press{
    int flag = 0;
    for (id object in self.array_city_serchNeed_in) {
        if ([object isEqualToString:self.str_city]) {
            flag = 1;
            break;
        }
    }
    
    if (flag == 0) {
        [self.dict setValue:self.str_city forKey:@"key"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notice" object:nil userInfo:self.dict];
        NSLog(@"ID::%@",self.str_city);
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        UIAlertController *alertVier  = [UIAlertController alertControllerWithTitle:@"提示" message:@"该城市已存在" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alertVier addAction:confirmAction];
                [self presentViewController:alertVier animated:YES completion:nil];
 
    }
}

详情

详情页面主要是使用SVG图片,需要通过CocoaPods引入第三方库。

使用方法为:

objectivec 复制代码
 NSString *svgFileName = [NSString stringWithFormat:@"/Users/liuyuanfu/Desktop/Icons-1.6.0/icons/%@.svg", iconName];
                            NSURL *svgURL = [NSURL fileURLWithPath:svgFileName];
                            if (svgURL) {
                                SVGKImage *svgImage = [SVGKImage imageWithContentsOfURL:svgURL];
                                if (svgImage) {
                                    // 将 SVG 图像转换为 UIImage
                                    UIImage *convertedImage = svgImage.UIImage;
                                    if (convertedImage) {
                                        // 将 UIImage 分配给 cell.imageView0.image
                                        cell.imageView0.image = convertedImage;
                                    } else {
                                    //判断是否是转换失败
                                        NSLog(@"SVG 转换失败");
                                    }
                                } else {
                                    // 判断是否为加载失败
                                    NSLog(@"SVG 加载失败");
                                }
                            }  else {
                                NSLog(@"SVG 导入失败");
                            }

总结

本次仿写刚开始的时候有很多的困难,网络申请有很多地方都看不懂,同时更新cell的时机也有很多的问题没考虑导致最后要改的地方很多。

但是在写完之后,还是学会了进行简单的网络申请以及引入第三方库。收获很多。

相关推荐
可爱发1 小时前
Mac下nvm无法安装node问题
macos
ehviwer2311 小时前
MathType7.9绿色和谐版激活补丁包下载
android·macos·ios·cocoa·媒体
Johnny Tong13 小时前
iOS 18 适配 Xcode 16 问题
ios·cocoa·xcode
sumatch17 小时前
Mac 创建 Python 虚拟环境
开发语言·python·macos
tubage202321 小时前
图像放大的软件PhotoZoom 9新功能介绍及安装激活使用指南
macos·电脑·photozoom·photozoom9
顶顶年华正版软件官方21 小时前
格式化u盘选择FAT还是NTFS U盘和硬盘格式化两者选谁
macos·ntfs格式
缘友一世1 天前
mac系统安装最新(截止2024.9.13)Oracle JDK操作记录
java·macos·oracle
AUV11071 天前
CleanClip for Mac 剪切板 粘贴工具 历史记录 安装(保姆级教程,新手小白轻松上手)
macos·mac·剪贴板·clipboard·剪贴板增强·复制历史·最强应用
鸿萌数据安全1 天前
鸿萌数据恢复服务:Mac 文件系统是如何影响 Mac 数据恢复的?
macos·mac数据恢复
七七r1 天前
【Mac】系统环境配置
macos