?1.獲取用戶當(dāng)前所在的位置
在infi中點(diǎn)擊加號(hào),選擇權(quán)限:當(dāng)用戶使用app的時(shí)候獲取位置權(quán)限.
填寫使用位置權(quán)限的目的.
?2.獲取用戶的經(jīng)緯度.
ViewController:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLLocationManagerDelegate協(xié)議
//位置管理器
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization() //請(qǐng)求當(dāng)用戶正在使用app的時(shí)候允許后臺(tái)得到用戶位置.只會(huì)彈出來一次
locationManager.delegate = self //位置管理器代理人是view controller對(duì)象.希望view controller能通過實(shí)現(xiàn)CLLocationManagerDelegate協(xié)議中的方法,獲取到當(dāng)前用戶位置信息
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers //設(shè)置需要的位置精度(三公里誤差精度)
locationManager.requestLocation() //請(qǐng)求用戶位置
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //requesLocation請(qǐng)求到了的話會(huì)執(zhí)行這個(gè)方法
let lon = locations[0].coordinate.longitude //精度.因?yàn)閘ocation可能實(shí)時(shí)變化(地圖app),所以是一個(gè)數(shù)組.我們只需要使用第一個(gè)獲取到的位置.
let lat = locations[0].coordinate.latitude //緯度
print(lon)
print(lat)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //requesLocation請(qǐng)求失敗的話會(huì)執(zhí)行這個(gè)方法
print(error)
}
}
?3.通過第三方服務(wù)獲取當(dāng)前天氣
(1)安裝cocoapods
https://dev.qweather.com/
在網(wǎng)站中可以找到,當(dāng)向 https://devapi.qweather.com/v7/weather/now?[請(qǐng)求參數(shù)] 發(fā)送請(qǐng)求時(shí),就可以得到當(dāng)前天氣.
通過依賴管理工具cocoapods命令行工具進(jìn)行依賴管理.在終端里對(duì)它進(jìn)行下載并安裝,
在Mac的啟動(dòng)臺(tái)上找到「終端」應(yīng)用,或者在觸控板上通過四指聚合來打開「啟動(dòng)臺(tái)—終端」。
在命令行輸入
sudo gem install cocoapods
(以超級(jí)管理員的身份,安裝cocoapods這個(gè)應(yīng)用.)
輸入電腦開機(jī)密碼.
?等待安裝成功.
?這里可能出現(xiàn)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.
這個(gè)bug,解決方式請(qǐng)參照博客:https://www.cnblogs.com/lysboke/p/17678896.html
(2)安裝功能包
在cocoapods官網(wǎng)https://cocoapods.org/的搜索欄搜索Alamofire.點(diǎn)擊進(jìn)入.
?用cocoapods安裝Alamofire.
在終端中輸入cd空格,將項(xiàng)目文件夾Weather拖入到cd后面.點(diǎn)擊回車.
?終端輸入
pod init
等待.完成之后打開Weather文件夾,發(fā)現(xiàn)成功創(chuàng)建Podfile文件.
?將Podfile拖入Xcode,Podfile自動(dòng)彈出.
加入代碼:
pod 'Alamofire'
保存并關(guān)閉Podfile.
?在終端輸入命令安裝功能包:
pod install
?關(guān)閉Xcode,從Weather文件中打開Weather.xcworkspace,可以看到項(xiàng)目結(jié)構(gòu)如下.
?4.利用和風(fēng)API獲取當(dāng)前位置的天氣信息
注冊(cè)和風(fēng)天氣賬號(hào).在和風(fēng)天氣中創(chuàng)建一個(gè)免費(fèi)的新項(xiàng)目.
https://console.qweather.com/#/apps/create-app/create
?得到key.
編寫代碼得到當(dāng)前經(jīng)緯度下的天氣數(shù)據(jù)信息.
import UIKit
import CoreLocation
import Alamofire //引入和風(fēng)API包
class ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLLocationManagerDelegate協(xié)議
//位置管理器
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization() //請(qǐng)求當(dāng)用戶正在使用app的時(shí)候允許后臺(tái)得到用戶位置.只會(huì)彈出來一次
locationManager.delegate = self //位置管理器代理人是view controller對(duì)象.希望view controller能通過實(shí)現(xiàn)CLLocationManagerDelegate協(xié)議中的方法,獲取到當(dāng)前用戶位置信息
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers //設(shè)置需要的位置精度(三公里誤差精度)
locationManager.requestLocation() //請(qǐng)求用戶位置
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //requesLocation請(qǐng)求到了的話會(huì)執(zhí)行這個(gè)方法
let lon = locations[0].coordinate.longitude //精度.因?yàn)閘ocation可能實(shí)時(shí)變化(地圖app),所以是一個(gè)數(shù)組.我們只需要使用第一個(gè)獲取到的位置.
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 in
if let data = response.value{
print(data)
}
} //請(qǐng)求和風(fēng)API的網(wǎng)址,得到當(dāng)前位置的天氣
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //requesLocation請(qǐng)求失敗的話會(huì)執(zhí)行這個(gè)方法
print(error)
}
}
為了在測(cè)試中使用http傳輸,在Info中新增一個(gè)key和Value:App Transport Security Settings,在它里邊再添加一個(gè)Allow Arbitrary Loads,Value設(shè)置為Yes.
?5.解析和風(fēng)API返回的JSON數(shù)據(jù)
在Xcode中的Podfile中添加如下:
pod 'SwiftyJSON', '~> 4.0'
?保存之后在終端輸入:
pod install
?下載之后引入JSON解析包,寫入代碼,測(cè)試.
import UIKit
import CoreLocation
import Alamofire //引入和風(fēng)API包
import SwiftyJSON //引入解析JSON數(shù)據(jù)的包
class ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLLocationManagerDelegate協(xié)議
//位置管理器
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization() //請(qǐng)求當(dāng)用戶正在使用app的時(shí)候允許后臺(tái)得到用戶位置.只會(huì)彈出來一次
locationManager.delegate = self //位置管理器代理人是view controller對(duì)象.希望view controller能通過實(shí)現(xiàn)CLLocationManagerDelegate協(xié)議中的方法,獲取到當(dāng)前用戶位置信息
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers //設(shè)置需要的位置精度(三公里誤差精度)
locationManager.requestLocation() //請(qǐng)求用戶位置
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //requesLocation請(qǐng)求到了的話會(huì)執(zhí)行這個(gè)方法
let lon = locations[0].coordinate.longitude //精度.因?yàn)閘ocation可能實(shí)時(shí)變化(地圖app),所以是一個(gè)數(shù)組.我們只需要使用第一個(gè)獲取到的位置.
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 in
if let data = response.value{
let weatherJSON = JSON(data)
print(weatherJSON)
}
} //請(qǐng)求和風(fēng)API的網(wǎng)址,得到當(dāng)前位置的天氣
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //requesLocation請(qǐng)求失敗的話會(huì)執(zhí)行這個(gè)方法
print(error)
}
}
?啟動(dòng)運(yùn)行:
?6.拿到天氣數(shù)據(jù)并展示在界面上
把溫度拖拽到ViewController中.
?同理,將天氣圖標(biāo)和用戶當(dāng)前所在的城市也拖拽到代碼區(qū).
?新建一個(gè)swift文件:
Weather.swift:
import Foundation
class Weather{
var temp = ""
var icon = ""
var city = ""
}
ViewController:
import UIKit
import CoreLocation
import Alamofire //引入和風(fēng)API包
import SwiftyJSON //引入解析JSON數(shù)據(jù)的包
class ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLLocationManagerDelegate協(xié)議
@IBOutlet weak var tempLable: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var cityLable: UILabel!
//位置管理器
let locationManager = CLLocationManager()
//Weather.swift實(shí)例化
let weather = Weather()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization() //請(qǐng)求當(dāng)用戶正在使用app的時(shí)候允許后臺(tái)得到用戶位置.只會(huì)彈出來一次
locationManager.delegate = self //位置管理器代理人是view controller對(duì)象.希望view controller能通過實(shí)現(xiàn)CLLocationManagerDelegate協(xié)議中的方法,獲取到當(dāng)前用戶位置信息
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers //設(shè)置需要的位置精度(三公里誤差精度)
locationManager.requestLocation() //請(qǐng)求用戶位置
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //requesLocation請(qǐng)求到了的話會(huì)執(zhí)行這個(gè)方法
let lon = locations[0].coordinate.longitude //精度.因?yàn)閘ocation可能實(shí)時(shí)變化(地圖app),所以是一個(gè)數(shù)組.我們只需要使用第一個(gè)獲取到的位置.
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 in
if 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結(jié)構(gòu)
self.weather.temp = "\(weatherJSON["now"]["temp"].stringValue)?"
self.weather.icon = weatherJSON["now"]["icon"].stringValue
self.tempLable.text = self.weather.temp
self.iconImageView.image = UIImage(named: self.weather.icon)
}
} //請(qǐng)求和風(fēng)API的網(wǎng)址,得到當(dāng)前位置的天氣
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //requesLocation請(qǐng)求失敗的話會(huì)執(zhí)行這個(gè)方法
print(error)
}
}
?啟動(dòng)測(cè)試:
?7.獲取用戶當(dāng)前所在的城市
ViewController:
import UIKit
import CoreLocation
import Alamofire //引入和風(fēng)API包
import SwiftyJSON //引入解析JSON數(shù)據(jù)的包
class ViewController: UIViewController, CLLocationManagerDelegate { //遵循CLLocationManagerDelegate協(xié)議
@IBOutlet weak var tempLable: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var cityLable: UILabel!
//位置管理器
let locationManager = CLLocationManager()
//Weather.swift實(shí)例化
let weather = Weather()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationManager.requestWhenInUseAuthorization() //請(qǐng)求當(dāng)用戶正在使用app的時(shí)候允許后臺(tái)得到用戶位置.只會(huì)彈出來一次
locationManager.delegate = self //位置管理器代理人是view controller對(duì)象.希望view controller能通過實(shí)現(xiàn)CLLocationManagerDelegate協(xié)議中的方法,獲取到當(dāng)前用戶位置信息
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers //設(shè)置需要的位置精度(三公里誤差精度)
locationManager.requestLocation() //請(qǐng)求用戶位置
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //requesLocation請(qǐng)求到了的話會(huì)執(zhí)行這個(gè)方法
let lon = locations[0].coordinate.longitude //精度.因?yàn)閘ocation可能實(shí)時(shí)變化(地圖app),所以是一個(gè)數(shù)組.我們只需要使用第一個(gè)獲取到的位置.
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 in
if 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結(jié)構(gòu)
self.weather.temp = "\(weatherJSON["now"]["temp"].stringValue)?"
self.weather.icon = weatherJSON["now"]["icon"].stringValue
self.tempLable.text = self.weather.temp
self.iconImageView.image = UIImage(named: self.weather.icon)
}
} //請(qǐng)求和風(fēng)API的網(wǎng)址,得到當(dāng)前位置的天氣
AF.request("https://geoapi.qweather.com/v2/city/lookup?location=\(lon),\(lat)&key=a91848aaab484a3599a703b139dfe87b").responseJSON { response in
if let data = response.value{
let cityJSON = JSON(data)
//處理數(shù)據(jù)
self.weather.city = cityJSON["location", 0, "name"].stringValue
//處理AI
self.cityLable.text = self.weather.city
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //requesLocation請(qǐng)求失敗的話會(huì)執(zhí)行這個(gè)方法
? ? ? ??cityLable.text = "獲取用戶城市失敗"
}
}
啟動(dòng)測(cè)試:文章來源:http://www.zghlxwxcb.cn/news/detail-697207.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-697207.html
到了這里,關(guān)于iOS開發(fā)Swift-10-位置授權(quán), cocoapods,API,天氣獲取,城市獲取-和風(fēng)天氣App首頁代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!