当前位置: 首页 > news >正文

iOS开发Swift-10-位置授权, cocoapods,API,天气获取,城市获取-和风天气App首页代码

 1.获取用户当前所在的位置

在infi中点击加号,选择权限:当用户使用app的时候获取位置权限.

填写使用位置权限的目的.

 2.获取用户的经纬度.

ViewController:

import UIKit
import CoreLocationclass ViewController: UIViewController, CLLocationManagerDelegate {    //遵循CLLocationManagerDelegate协议//位置管理器let locationManager = CLLocationManager()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.locationManager.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次locationManager.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers    //设置需要的位置精度(三公里误差精度)locationManager.requestLocation()    //请求用户位置}func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {  //requesLocation请求到了的话会执行这个方法let lon = locations[0].coordinate.longitude   //精度.因为location可能实时变化(地图app),所以是一个数组.我们只需要使用第一个获取到的位置.let lat = locations[0].coordinate.latitude    //纬度print(lon)print(lat)}func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {    //requesLocation请求失败的话会执行这个方法print(error)}}

 3.通过第三方服务获取当前天气

(1)安装cocoapods

https://dev.qweather.com/

在网站中可以找到,当向 https://devapi.qweather.com/v7/weather/now?[请求参数] 发送请求时,就可以得到当前天气.

通过依赖管理工具cocoapods命令行工具进行依赖管理.在终端里对它进行下载并安装,

在Mac的启动台上找到「终端」应用,或者在触控板上通过四指聚合来打开「启动台—终端」。

在命令行输入

sudo gem install cocoapods

(以超级管理员的身份,安装cocoapods这个应用.)

输入电脑开机密码.

 等待安装成功.

 这里可能出现Error installing cocoapods:
The last version of activesupport (>= 5.0, < 8) to support your Ruby & RubyGems was 6.1.7.6. Try installing it with `gem install activesupport -v 6.1.7.6` and then running the current command again
activesupport requires Ruby version >= 2.7.0. The current ruby version is 2.6.10.210.

这个bug,解决方式请参照博客:https://www.cnblogs.com/lysboke/p/17678896.html

(2)安装功能包

在cocoapods官网https://cocoapods.org/的搜索栏搜索Alamofire.点击进入.

 用cocoapods安装Alamofire.

在终端中输入cd空格,将项目文件夹Weather拖入到cd后面.点击回车.

 终端输入

pod init

等待.完成之后打开Weather文件夹,发现成功创建Podfile文件.

 将Podfile拖入Xcode,Podfile自动弹出.

加入代码:

  pod 'Alamofire'

保存并关闭Podfile.

 在终端输入命令安装功能包:

pod install

 关闭Xcode,从Weather文件中打开Weather.xcworkspace,可以看到项目结构如下.

 4.利用和风API获取当前位置的天气信息

注册和风天气账号.在和风天气中创建一个免费的新项目.

https://console.qweather.com/#/apps/create-app/create

 得到key.

编写代码得到当前经纬度下的天气数据信息.

import UIKit
import CoreLocation
import Alamofire   //引入和风API包class ViewController: UIViewController, CLLocationManagerDelegate {    //遵循CLLocationManagerDelegate协议//位置管理器let locationManager = CLLocationManager()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.locationManager.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次locationManager.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers    //设置需要的位置精度(三公里误差精度)locationManager.requestLocation()    //请求用户位置}func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {  //requesLocation请求到了的话会执行这个方法let lon = locations[0].coordinate.longitude   //精度.因为location可能实时变化(地图app),所以是一个数组.我们只需要使用第一个获取到的位置.let lat = locations[0].coordinate.latitude    //纬度//print(lon)//print(lat)AF.request("https://devapi.qweather.com/v7/weather/now?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response inif let data = response.value{print(data)}}      //请求和风API的网址,得到当前位置的天气}func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {    //requesLocation请求失败的话会执行这个方法print(error)}
}

为了在测试中使用http传输,在Info中新增一个key和Value:App Transport Security Settings,在它里边再添加一个Allow Arbitrary Loads,Value设置为Yes.

 5.解析和风API返回的JSON数据

在Xcode中的Podfile中添加如下:

pod 'SwiftyJSON', '~> 4.0'

 保存之后在终端输入:

pod install

 下载之后引入JSON解析包,写入代码,测试.

import UIKit
import CoreLocation
import Alamofire   //引入和风API包
import SwiftyJSON   //引入解析JSON数据的包class ViewController: UIViewController, CLLocationManagerDelegate {    //遵循CLLocationManagerDelegate协议//位置管理器let locationManager = CLLocationManager()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.locationManager.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次locationManager.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers    //设置需要的位置精度(三公里误差精度)locationManager.requestLocation()    //请求用户位置}func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {  //requesLocation请求到了的话会执行这个方法let lon = locations[0].coordinate.longitude   //精度.因为location可能实时变化(地图app),所以是一个数组.我们只需要使用第一个获取到的位置.let lat = locations[0].coordinate.latitude    //纬度//print(lon)//print(lat)AF.request("https://devapi.qweather.com/v7/weather/now?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response inif let data = response.value{let weatherJSON = JSON(data)print(weatherJSON)}}      //请求和风API的网址,得到当前位置的天气}func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {    //requesLocation请求失败的话会执行这个方法print(error)}
}

 启动运行:

 6.拿到天气数据并展示在界面上

把温度拖拽到ViewController中.

 同理,将天气图标和用户当前所在的城市也拖拽到代码区.

 新建一个swift文件:

Weather.swift:

import Foundationclass Weather{var temp = ""var icon = ""var city = ""
}

ViewController:

import UIKit
import CoreLocation
import Alamofire   //引入和风API包
import SwiftyJSON   //引入解析JSON数据的包class ViewController: UIViewController, CLLocationManagerDelegate {    //遵循CLLocationManagerDelegate协议@IBOutlet weak var tempLable: UILabel!@IBOutlet weak var iconImageView: UIImageView!@IBOutlet weak var cityLable: UILabel!//位置管理器let locationManager = CLLocationManager()//Weather.swift实例化let weather = Weather()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.locationManager.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次locationManager.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers    //设置需要的位置精度(三公里误差精度)locationManager.requestLocation()    //请求用户位置}func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {  //requesLocation请求到了的话会执行这个方法let lon = locations[0].coordinate.longitude   //精度.因为location可能实时变化(地图app),所以是一个数组.我们只需要使用第一个获取到的位置.let lat = locations[0].coordinate.latitude    //纬度//print(lon)//print(lat)AF.request("https://devapi.qweather.com/v7/weather/now?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response inif let data = response.value{let weatherJSON = JSON(data)//print(weatherJSON["now"]["temp"])    //或weatherJSON["now", "temp"]//print(weatherJSON["refer"]["sources"][0])     //weatherJSON["refer", "sources", 0]//MVC结构self.weather.temp = "\(weatherJSON["now"]["temp"].stringValue)˚"self.weather.icon = weatherJSON["now"]["icon"].stringValueself.tempLable.text = self.weather.tempself.iconImageView.image = UIImage(named: self.weather.icon)}}      //请求和风API的网址,得到当前位置的天气}func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {    //requesLocation请求失败的话会执行这个方法print(error)}
}

 启动测试:

 7.获取用户当前所在的城市

ViewController:

import UIKit
import CoreLocation
import Alamofire   //引入和风API包
import SwiftyJSON   //引入解析JSON数据的包class ViewController: UIViewController, CLLocationManagerDelegate {    //遵循CLLocationManagerDelegate协议@IBOutlet weak var tempLable: UILabel!@IBOutlet weak var iconImageView: UIImageView!@IBOutlet weak var cityLable: UILabel!//位置管理器let locationManager = CLLocationManager()//Weather.swift实例化let weather = Weather()override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view.locationManager.requestWhenInUseAuthorization()    //请求当用户正在使用app的时候允许后台得到用户位置.只会弹出来一次locationManager.delegate = self    //位置管理器代理人是view controller对象.希望view controller能通过实现CLLocationManagerDelegate协议中的方法,获取到当前用户位置信息locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers    //设置需要的位置精度(三公里误差精度)locationManager.requestLocation()    //请求用户位置}func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {  //requesLocation请求到了的话会执行这个方法let lon = locations[0].coordinate.longitude   //精度.因为location可能实时变化(地图app),所以是一个数组.我们只需要使用第一个获取到的位置.let lat = locations[0].coordinate.latitude    //纬度//print(lon)//print(lat)AF.request("https://devapi.qweather.com/v7/weather/now?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response inif let data = response.value{let weatherJSON = JSON(data)//print(weatherJSON["now"]["temp"])    //或weatherJSON["now", "temp"]//print(weatherJSON["refer"]["sources"][0])     //weatherJSON["refer", "sources", 0]//MVC结构self.weather.temp = "\(weatherJSON["now"]["temp"].stringValue)˚"self.weather.icon = weatherJSON["now"]["icon"].stringValueself.tempLable.text = self.weather.tempself.iconImageView.image = UIImage(named: self.weather.icon)}}      //请求和风API的网址,得到当前位置的天气AF.request("https://geoapi.qweather.com/v2/city/lookup?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response inif let data = response.value{let cityJSON = JSON(data)//处理数据self.weather.city = cityJSON["location", 0, "name"].stringValue//处理AIself.cityLable.text = self.weather.city}}}func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {    //requesLocation请求失败的话会执行这个方法

        cityLable.text = "获取用户城市失败"

}}

启动测试:

相关文章:

iOS开发Swift-10-位置授权, cocoapods,API,天气获取,城市获取-和风天气App首页代码

1.获取用户当前所在的位置 在infi中点击加号,选择权限:当用户使用app的时候获取位置权限. 填写使用位置权限的目的. 2.获取用户的经纬度. ViewController: import UIKit import CoreLocationclass ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLL…...

CNN(七):ResNeXt-50算法的思考

&#x1f368; 本文为&#x1f517;365天深度学习训练营中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊|接辅导、项目定制 在进行ResNeXt-50实战练习时&#xff0c;我也跟其他学员一样有这个疑惑&#xff0c;如下图所示&#xff1a; 反复查看代码&#xff0c;仍然有…...

【人月神话】深入了解软件工程和项目管理

文章目录 &#x1f468;‍⚖️《人月神话》的主要观点&#x1f468;‍&#x1f3eb;《人月神话》的主要内容&#x1f468;‍&#x1f4bb;作者介绍 &#x1f338;&#x1f338;&#x1f338;&#x1f337;&#x1f337;&#x1f337;&#x1f490;&#x1f490;&#x1f490;&a…...

52、基于函数式方式开发 Spring WebFlux 应用

★ Spring WebFlux的两种开发方式 1. 采用类似于Spring MVC的注解的方式来开发。此时开发时感觉Spring MVC差异不大&#xff0c;但底层依然是反应式API。2. 使用函数式编程来开发★ 使用函数式方式开发Web Flux 使用函数式开发WebFlux时需要开发两个组件&#xff1a; ▲ Han…...

MySQL的用户管理

1、MySQL的用户管理 &#xff08;1&#xff09;创建用户 create user zhang3 identified by 123123;表示创建名称为zhang3的用户&#xff0c;密码设为123123。 &#xff08;2&#xff09;了解user表 1&#xff09;查看用户 select host,user,authentication_string,select…...

LeetCode //C - 114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child …...

利用transform和border 创造简易图标,以适应uniapp中多字体大小情况下的符号问题

heml: <text class"icon-check"></text> css: .icon-check {border: 2px solid black;border-left: 0;border-top: 0;height: 12px;width: 6px;transform-origin: center;transform: rotate(45deg);} 实际上就是声明一个带边框的div 将其中相邻的两边去…...

C/C++指针函数与函数指针

一、指针函数 指针函数&#xff1a;本质为一个函数&#xff0c;返回值为指针指针函数&#xff1a;如果一个函数的返回值是指针类型&#xff0c;则称为指针函数用指针作为函数的返回值的好处&#xff1a;可以从被调函数向主函数返回大量的数据&#xff0c;常用于返回结构体指针。…...

30天入门Python(基础篇)——第1天:为什么选择Python

文章目录 专栏导读作者有话说为什么学习Python原因1(总体得说)原因2(就业说) Python的由来(来自百度百科)Python的版本 专栏导读 &#x1f525;&#x1f525;本文已收录于《30天学习Python从入门到精通》 &#x1f251;&#x1f251;本专栏专门针对于零基础和需要重新复习巩固…...

智慧公厕破解公共厕所管理的“孤岛现象”

在现代社会中&#xff0c;公共厕所是城市管理中的一项重要任务。然而&#xff0c;经常会出现公厕管理的“孤岛现象”&#xff0c;即每个公厕都是独立运作&#xff0c;缺乏统一的管理和监控机制。针对这一问题&#xff0c;智慧公厕的出现为解决公共厕所管理难题带来了新的方案。…...

excel中删除重复项

数据如图&#xff1a; 要删除姓名这一列的重复项&#xff0c;操作&#xff1a; (1)选中姓名这一列(2)点击“数据”(3)点击“删除重复项" 这是excel会自动检测出还有别的关联列 直接默认&#xff0c;点击删除重复项...弹出下面的界面 因为我们只要删除“姓名”列的重复值&…...

2023-9-8 求组合数(三)

题目链接&#xff1a;求组合数 III #include <iostream> #include <algorithm>using namespace std;typedef long long LL;int p;int qmi(int a, int k) {int res 1;while(k){if(k & 1) res (LL) res * a % p;k >> 1;a (LL) a * a % p;}return res; }…...

01 - Apache Seatunnel 源码调试

1.下载源码 https://github.com/apache/seatunnel.git2.编译 mvn clean package -pl seatunnel-dist -am -Dmaven.test.skiptrue3. 下载驱动 sh bin/install-plugin.sh 4.测试类 选择 seatunnel-examples ├── seatunnel-engine-examples ├── seatunnel-flink-connecto…...

UVA-12325 宝箱 题解答案代码 算法竞赛入门经典第二版

GitHub - jzplp/aoapc-UVA-Answer: 算法竞赛入门经典 例题和习题答案 刘汝佳 第二版 根据书上的方法来做&#xff0c;是比较简单的题目。关键在于知道等体积时的枚举法。不过数据大小可能很大&#xff0c;虽然输入可以用int处理&#xff0c;但是 体积*价值 后&#xff0c;需要l…...

烟感报警器单片机方案开发,解决方案

烟感报警器也叫做烟雾报警器。烟感报警器适用于火灾发生时有大量烟雾&#xff0c;而正常情况下无烟的场所。例如写字楼、医院、学校、博物馆等场所。烟感报警器一般安装于所需要保护或探测区域的天花板上&#xff0c;因火灾中烟雾比空气轻&#xff0c;更容易向上飘散&#xff0…...

【JavaEE】_CSS引入方式与选择器

目录 1. 基本语法格式 2. 引入方式 2.1 内部样式 2.2 内联样式 2.3 外部样式 3. 基础选择器 3.1 标签选择器 3.2 类选择器 3.3 ID选择器 4. 复合选择器 4.1 后代选择器 4.2 子选择器 4.3 并集选择器 4.4 伪类选择器 1. 基本语法格式 选择器若干属性声明 2. 引入…...

【8】shader写入类中

上一篇将 vao vbo写入类中进行封装&#xff0c;本篇将shader进行封装。 Shader shader("res/shaders/Basic.shader");shader.Bind(); shader.SetUniform4f("u_Color", 0.2f, 0.3f, 0.8f, 1.0f);shader.h #pragma once#include <string> #include &l…...

Servlet注册迭代史

Servlet注册迭代史 1、第一代&#xff0c;xml注册 <web-app><display-name>Archetype Created Web Application</display-name><!-- 定义一个Servlet --><servlet><!-- Servlet的名称&#xff0c;用于在配置中引用 --><servlet-name&…...

合创汽车V09纵享商务丝滑?预售价32万元起,正式宣布大规模生产

合创汽车正式宣布&#xff0c;旗下新款车型V09已于9月10日开始大规模生产&#xff0c;并预计将于10月13日正式上市。V09作为中大型纯电动MPV的代表之一&#xff0c;备受瞩目。该车型是广汽新能源和蔚来汽车共同成立的广汽蔚来改为广汽集团和珠江投管共同投资的高端品牌——合创…...

49. 视频热度问题

文章目录 实现一题目来源 谨以此笔记献给浪费掉的两个小时。 此题存在多处疑点和表达错误的地方&#xff0c;如果你看到了这篇文章&#xff0c;劝你跳过该题。 该题对提升HSQL编写能力以及思维逻辑能力毫无帮助。 实现一 with info as (-- 将数据与 video_info 关联&#x…...

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

反向工程与模型迁移:打造未来商品详情API的可持续创新体系

在电商行业蓬勃发展的当下&#xff0c;商品详情API作为连接电商平台与开发者、商家及用户的关键纽带&#xff0c;其重要性日益凸显。传统商品详情API主要聚焦于商品基本信息&#xff08;如名称、价格、库存等&#xff09;的获取与展示&#xff0c;已难以满足市场对个性化、智能…...

解锁数据库简洁之道:FastAPI与SQLModel实战指南

在构建现代Web应用程序时&#xff0c;与数据库的交互无疑是核心环节。虽然传统的数据库操作方式&#xff08;如直接编写SQL语句与psycopg2交互&#xff09;赋予了我们精细的控制权&#xff0c;但在面对日益复杂的业务逻辑和快速迭代的需求时&#xff0c;这种方式的开发效率和可…...

前端导出带有合并单元格的列表

// 导出async function exportExcel(fileName "共识调整.xlsx") {// 所有数据const exportData await getAllMainData();// 表头内容let fitstTitleList [];const secondTitleList [];allColumns.value.forEach(column > {if (!column.children) {fitstTitleL…...

1.3 VSCode安装与环境配置

进入网址Visual Studio Code - Code Editing. Redefined下载.deb文件&#xff0c;然后打开终端&#xff0c;进入下载文件夹&#xff0c;键入命令 sudo dpkg -i code_1.100.3-1748872405_amd64.deb 在终端键入命令code即启动vscode 需要安装插件列表 1.Chinese简化 2.ros …...

高危文件识别的常用算法:原理、应用与企业场景

高危文件识别的常用算法&#xff1a;原理、应用与企业场景 高危文件识别旨在检测可能导致安全威胁的文件&#xff0c;如包含恶意代码、敏感数据或欺诈内容的文档&#xff0c;在企业协同办公环境中&#xff08;如Teams、Google Workspace&#xff09;尤为重要。结合大模型技术&…...

用docker来安装部署freeswitch记录

今天刚才测试一个callcenter的项目&#xff0c;所以尝试安装freeswitch 1、使用轩辕镜像 - 中国开发者首选的专业 Docker 镜像加速服务平台 编辑下面/etc/docker/daemon.json文件为 {"registry-mirrors": ["https://docker.xuanyuan.me"] }同时可以进入轩…...

大数据学习(132)-HIve数据分析

​​​​&#x1f34b;&#x1f34b;大数据学习&#x1f34b;&#x1f34b; &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 用力所能及&#xff0c;改变世界。 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4…...

服务器--宝塔命令

一、宝塔面板安装命令 ⚠️ 必须使用 root 用户 或 sudo 权限执行&#xff01; sudo su - 1. CentOS 系统&#xff1a; yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh2. Ubuntu / Debian 系统…...

蓝桥杯 冶炼金属

原题目链接 &#x1f527; 冶炼金属转换率推测题解 &#x1f4dc; 原题描述 小蓝有一个神奇的炉子用于将普通金属 O O O 冶炼成为一种特殊金属 X X X。这个炉子有一个属性叫转换率 V V V&#xff0c;是一个正整数&#xff0c;表示每 V V V 个普通金属 O O O 可以冶炼出 …...