当前位置:网站首页>Swift creates weather app
Swift creates weather app
2022-07-25 09:52:00 【yueliangmua】
From learning iOS Development up to now , It's been a while since I started , For the first time, we can realize a app, It's still very fulfilling , The following is a brief record and sharing of the implementation process .
Catalog
3、 ... and 、 Initiate a network request based on coordinates
5、 ... and 、 Connect the control content with the obtained data
6、 ... and 、 Configure the second page
7、 ... and 、 Initiate a network request based on the city name
8、 ... and 、 Separate and simplify code
First, the final effect


The basic idea
- use Main.storyboard Build the original page
- Request location
- Initiate a network request based on coordinates
- Analyze weather data
- Connect the control content with the obtained data
- Configure the second page
- Initiate a network request based on the city name
- MVC Separate code
One 、 Build a page
1、 Create project files
2、 choice Main.storyboard file , Click the plus sign in the upper right corner to add the required control , And set the constraints of the control through the function keys below , Complete the construction of the first page .

After setting up the page , As shown in the figure below .

Two 、 Request location
To show the weather , First, get the location information of the current device , At this point, you can select simulator , Click the upper navigation bar and click Features、Location、Custom Location

Then an editable box will pop up , Input the latitude and accuracy of the position you want the simulator to be in and click OK, This means that the simulated fuselage is at this coordinate ( Longitude and latitude can be checked at any place on Gaode map or Baidu map ).

After setting the location of the simulator, you can use the code to obtain the current location .
Here we need to use a third-party library CoreLocation
First, import. CoreLocation
import CoreLocationThis function pack can be used to obtain the current location of the device , First instantiate the object of this type and set the proxy , Then call the method to get the location .
class ViewController: UIViewController, CLLocationManagerDelegate{// Setting agent
let locationManger = CLLocationManager()// Instantiate objects
override func viewDidLoad(){
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()// Request authorization current location
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers// Set the accuracy of the acquired position to within three kilometers
locationManager.requestLocation()// To obtain position
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {// Realization delegat The method of gets the position and assigns it to the two defined quantities , Whether the output verification result is correct
let lon = locations[0].coordinate.longitude
let lat = locations[0].coordinate.latitude
print(lon,lat)
}
func locationManager(_ manager:CLLocationManager, didFailWithError error:Error) {
print(error)// Call when getting the location fails
}
}
But after running it found that , The program cannot get the location information normally , This is because a description needs to be added when requesting location .
open info.plist file , Click the plus sign on the first line , Select... In the pop-up selection box Privacy-Location Always and When In Use Usage Descrip This one , stay value Enter a line of description information in the column , To inform the user of the description of the operation .
Now you can see , After operation , It can correctly output the coordinates of the current position .
3、 ... and 、 Initiate a network request based on coordinates
To complete this function, you need to introduce a third-party library Alamofire. Here is how to import this library .
1、 install cocopods, After installed , Open the terminal ,cd To the project folder , Enter the command pod init, You'll find one more podfile file . At this time in github Mid search Alamofire, Choose installation, You will see the use cocopods The command to install this feature pack , Copy the command to podfile In file , Enter the command pod install You can import the function package .( The first installation may take a long time , Because it will download all the third-party library indexes ) Abnormal situation : If the download fails, it may be due to network restrictions .




When everything is ready , You can officially start the network request .
First, find a website with weather data , By requesting the website API Get back JSON data , Update the interface data after parsing . I use the Hefeng weather development platform https://dev.qweather.com After registering, get your key, according to API The development documents know the required parameters .
According to the Alamofire The following code snippet can be obtained by using the
AF.request("https://devapi.qweather.com/v7/weather/now?location=/(lon),/(lat)&key= Their own key").responseJSON { response in// obtain JSON Format
if let data = response.value{
}
}In this way, the weather data is successfully obtained , The data result exists data in .
Four 、 Analyze weather data
here data The data in is JSON Format , So we need to introduce third-party libraries SwiftJSON to JSON Data analysis ,SwiftJSON Please refer to Alamofire The introduction of . The final code segment is
AF.request("https://devapi.qweather.com/v7/weather/now?location=/(lon),/(lat)&key= Their own key").responseJSON { response in// obtain JSON Format
if let data = response.value{
let weatherJSON = JSON(data)
print(weatherJSON)
}
}At this point, the data will be successfully converted , The output is

5、 ... and 、 Connect the control content with the obtained data
adopt JSON Get the data through the chain call of , Here is an example of the code
self.label.text = weatherJSON["now","temp"].stringValue
self.iconImageView.image = UIImage(named: weatherJSON["now","icon"].stringValue)contrast JSON Format data can be found in this way now Inside temp Data and now Inside icon Data and assignment
6、 ... and 、 Configure the second page
adopt Main.storyboard Drag a new one with the plus sign in the upper right corner ViewController In the interface, the function area on the right will class Specify as new QueryViewController class , It is the second function interface to find the weather of a specified city .
Click the search button in the first interface to jump to the second interface , Hold down ctrl Click the search control and drag to QueryViewController. After the page is built, the effect is as follows

To display the current city when jumping to the second interface , It needs to be implemented in the first interface prepare Method , The code snippet is as follows
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? QueryViewController{
// What determines whether to jump is QueryViewController Interface
vc.currentCity = weather.city// The current city information of the second interface
}
}In addition to QueryViewController in , And the following 2 Features
1. Click the back button to return to the first page, but the data does not change
2. Click the query weather button to send the entered city back to the first page for weather query and display
The code implementation is as follows
protocol QueryViewControllerDelegate {// Custom protocol , If it is QueryViewController Class needs to implement the methods in the Protocol
func didChangeCity(city: String)
}
class QueryViewController: UIViewController {
var currentCity = ""
var delegate: QueryViewControllerDelegate?
@IBOutlet weak var currentCityLabel: UILabel!
@IBOutlet weak var cityTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cityTextField.becomeFirstResponder()// focusing //cityTextField.resignFirstResponder// Unfocus
currentCityLabel.text = currentCity
}
@IBAction func back(_ sender: Any) {// Click to return to the first interface without any operation
dismiss(animated: true)
}
@IBAction func query(_ sender: Any) {// Click to return to the first interface. If the content of the input box is not for air conditioning didChangeCity Method
dismiss(animated: true)
if !cityTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty{
delegate?.didChangeCity(city: cityTextField.text!)
}
}
}7、 ... and 、 Initiate a network request based on the city name
Pass the first QueryViewController Return the city name to make a network request , First of all, because Chinese characters cannot be used as parameters in city names, you need to pass Alamofire Bring one with you parameters Convert the city name into URL code , adopt AF.request After obtaining city information , And then through the city id Get the weather of the city .
The implementation code of the method is as follows
import Foundation
import Alamofire
import SwiftyJSON
extension ViewController: QueryViewControllerDelegate{
func didChangeCity(city: String) {
AF.request(kQWeatherCityPath,parameters: getParameters(city)).responseJSON{// You can see from the development documents that when the parameter is the city name , You can also query , However, due to the Chinese form, it needs to pass Alamofire Self contained parameters convert to URL code
response in
if let data = response.value{
let cityJSON = JSON(data)
self.showCity(cityJSON)
let cityID = cityJSON["location",0,"id"].stringValue// adopt JSON Find the city id
AF.request(kQWeatherNowPath,parameters: self.getParameters(cityID)).responseJSON { response in// Use the city ID Find the weather
if let data = response.value{
let weatherJSON = JSON(data)
self.showWeather(weatherJSON)
// print(weatherJSON["now","temp"])
}
}
}
}
}
}import Foundation
import SwiftyJSON
extension ViewController{
func showWeather(_ weatherJSON: JSON){
// data
self.weather.temp = "\(weatherJSON["now","temp"].stringValue)°"
self.weather.icon = weatherJSON["now","icon"].stringValue
//UI
self.tempLabel.text = self.weather.temp
self.iconImageView.image = UIImage(named: self.weather.icon)
}
func showCity(_ cityJSON: JSON){
// data
weather.city = cityJSON["location",0,"adm2"].stringValue
//UI
cityLabel.text = weather.city
}
func getParameters(_ location: String) -> [String: String]{
["location": location, "key": kQWeatherWebKey]
}
}Don't forget to set the proxy of the first interface at this time
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? QueryViewController{
// What determines whether to jump is QueryViewController Interface
vc.currentCity = weather.city// The current city information of the second interface
vc.delegate = self// Setting agent
}
}After completing these, the function of weather will be basically realized
8、 ... and 、 Separate and simplify code
1. Put the constants used many times in the same file
2. Put the method used many times in the same file
3. Define a Model Put data variables in the file
4. Put the codes of the two controllers in two files respectively
As shown in the figure below


边栏推荐
- Learning new technology language process
- Surfaceview flash screen (black problem)
- 【数据挖掘】第四章 分类任务(决策树)
- First knowledge of opencv4.x --- drawing shapes on images
- Mixed supervision for surface defect detection: from weakly to fully supervised learning
- Evolution based on packnet -- review of depth estimation articles of Toyota Research Institute (TRI) (Part 2)
- First knowledge of opencv4.x --- image convolution
- matlab绘图|坐标轴axis的一些常用设置
- 单目深度估计自监督模型Featdepth解读(上)——论文理解和核心源码分析
- [dimension reduction strike] Hilbert curve
猜你喜欢

深度估计自监督模型monodepth2论文总结和源码分析【理论部分】

初识Opencv4.X----图像直方图均衡

matlab如何导入大量数据

How to install pytorch—— A most simple and effective method!

matlab如何导入大量数据

单目深度估计自监督模型Featdepth解读(上)——论文理解和核心源码分析

First knowledge of opencv4.x --- image histogram equalization

CCF 201509-4 高速公路

Get to know opencv4.x for the first time --- add Gaussian noise to the image

SD/SDIO/EMMC
随机推荐
Flutter rive multi state example
【机器翻译】SCONES——用多标签任务做机器翻译
T5论文总结
无向连通图邻接矩阵的创建输出广度深度遍历
数据分析业务核心
Chmod and chown invalidate the files of the mounted partition
TensorFlow2 安装快速避坑汇总
Create personal extreme writing process - reprint
单目深度估计自监督模型Featdepth解读(下)——openMMLab框架使用
First knowledge of opencv4.x --- image histogram drawing
Minkowskiengine installation
CCF 201503-3 节日
深度估计自监督模型monodepth2论文总结和源码分析【理论部分】
First knowledge of opencv4.x ---- mean filtering
First acquaintance with opencv4.x --- ROI interception
Raspberry sect door ban system based on face recognition
How to import a large amount of data in MATLAB
Bracket matching problem
目标检测与分割之MaskRCNN代码结构流程全面梳理+总结
【数据挖掘】第四章 分类任务(决策树)