Swift 網路請求使用 Moya part1

LULU
Nov 3, 2021

--

由於工作需求接觸到很多好玩的套件

今天跟大家分享一下一個容易閱讀及方便維護的網路請求方式

首先~來看一下這張鼎鼎大明的圖

都已經一層一層地幫你整理好了

安裝Moya

  1. 建立Podfile
# pod init

2. 編輯Podfile

pod 'Moya'

3.執行pod install來安裝第三方套件

# pod install

實作

  1. 宣告一個enum定義每個請求
enum WeatherData {static let apiKey = "qwertyuiop12345"(請填自己的apiKey)//有幾個api就列出幾個
case currentWeather(cityName: String)
}

2.擴充這個enum並遵守TargetType協議

若是以city name取資料,網址如下

extension WeatherData: TargetType {var baseURL: URL {return URL(string: "https://api.openweathermap.org/")!}var path: String {switch self {case .currentWeather:return "data/2.5/weather"}}var method: Moya.Method {switch self {case .currentWeather:return .get}}var task: Task {switch self {case .currentWeather(let cityName):return .requestParameters(parameters: ["q": cityName, "appid": WeatherData.apiKey], encoding: URLEncoding.default)}}var headers: [String : String]? {return ["Content-type": "application/json"]}}

3.使用MoyaProvider發出請求並接收回傳值

以上~就能順利印出 currentWeatherResponse的資料了~

今天 part1 先這樣~

--

--

LULU
LULU

Written by LULU

Hi👋 I’m iOS developer, I hope I can grow with you guys ☺️ Let’s learn more together.

No responses yet