美文网首页iOS-项目实战
Moya+RxSwift展示天气数据

Moya+RxSwift展示天气数据

作者: 向日葵的夏天_summer | 来源:发表于2017-12-01 16:23 被阅读0次

RxSwift结合Moya获取天气数据,并结合tableView进行展示

效果图

Moya.gif

一. cocoPod安装RxSwift, RxCocoa, Alamofire, Moya/RxSwift

二. 模型

  1. 枚举表示根据地理位置获取天气数据

     enum SkyAPI {
     //根据经纬度获取天气数据
     case getWeatherData(Location)
     }
    
  2. 遵守TargetType协议,创建MoyaProvider

     extension SkyAPI: TargetType {
     var headers: [String : String]? {
         return nil
     }
    
     var baseURL: URL {
         return URL(string: BASE_URL)!
     }
     
     var path: String {
         switch self {
             case .getWeatherData(let location):
             return KEY + "/" + "\(location.latitude),\(location.longitude)"
         }
     }
     
     var method: Moya.Method {
         return .get
     }
     
     var sampleData: Data {
         return "找不到数据".data(using: String.Encoding.utf8)!
     }
     
     var validate: Bool {
         return true
     }
     
     var task: Task {
         return .requestPlain
     }
    
     }
    
  3. 天气模型

     struct Sky {
     
     var humidity: Double?
     var time: TimeInterval?
     var windSpeed: Double?
     var summary: String?
     var tempera: Double?
     
     init(dict: [String: Any]?) {
         guard let dict = dict else {return}
         print(dict)
         self.humidity = dict["humidity"] as? Double
         self.time = dict["time"] as? Double
         self.windSpeed = dict["windSpeed"] as? Double
         self.summary = dict["summary"] as? String
         self.tempera = ((dict["temperatureMin"] as? Double ?? 0 ) - 32) / 1.8
     }
     }   
    
     class SkyModel: NSObject {
         var currently: Sky?
         var daily: [Sky]?
     
     init?(dict: [String: Any]?) {
         guard let dict = dict else{return nil}
         var skyDays = [Sky]()
         self.currently = Sky(dict: dict["currently"] as? [String: Any])
         if let daily = dict["daily"] as? [String: Any] {
             if let days = daily["data"] as? [[String: Any]] {
                 for day in days {
                     skyDays.append(Sky(dict: day))
                 }
             }
         }
         self.daily = skyDays
     }
     }
    
  4. 请求数据

     class SkyViewModel: NSObject {
    
     override init() {
         super.init()
     }
    
     func loadWeatherData(location: Location) -> Observable<SkyModel?> {
         let provider = MoyaProvider<SkyAPI>()
         return Observable.create({ (observer) -> Disposable in
             provider.request(.getWeatherData(location), completion: { (response) in
                 switch response {
                 case let .success(result):
                     guard let result = try? result.mapJSON() else {return}
                     observer.onNext(SkyModel(dict: result as? [String: Any]))
                     observer.onCompleted()
                     
                 case let .failure(error):
                     observer.onError(error)
                 }
             })
             return Disposables.create()
         })
     }
    
     }
    

三.展示数据

  1. 定位,获取地理位置

     func setupLocationManager() {
         locationManager = CLLocationManager()
         locationManager.delegate = self
         locationManager.desiredAccuracy = kCLLocationAccuracyBest
     }
     
     func startLocation() {
         locationManager.requestWhenInUseAuthorization()
         locationManager.startUpdatingLocation()
     }
     
     extension SkyViewController: CLLocationManagerDelegate {
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
         let location = locations.last
         let coordinate = location?.coordinate
         if let latitide = coordinate?.latitude, let longitude = coordinate?.longitude {
             myLocation = Location(name: "", latitude: latitide, longitude: longitude)
             viewModel.loadWeatherData(location: myLocation)
                 .subscribe(onNext: {
                     if let skyModel = $0 {
                         self.skyModel = skyModel
                         self.setupUI()
                     }
                 }, onError: {
                     print($0)
                 })
                 .disposed(by: disposedBag)
         }
         locationManager.stopUpdatingLocation()
     }
     }
    
  2. 创建tableView,indicatorView

     func setupUI() {
     indicatorView.stopAnimating()
     indicatorView.removeFromSuperview()
     
     tableView = UITableView()
     tableView.register(SkyTableViewCell.self, forCellReuseIdentifier: "SkyCellID")
     tableView.tableFooterView = UIView()
     tableView.delegate = self
     tableView.dataSource = self
     view.addSubview(tableView)
     tableView.snp.makeConstraints { (make) in
         make.edges.equalToSuperview()
     }
     }
     
     func setupIndicator() {
     indicatorView = UIActivityIndicatorView()
     view.addSubview(indicatorView)
     indicatorView.startAnimating()
     indicatorView.activityIndicatorViewStyle = .gray
     
     indicatorView.snp.makeConstraints { (make) in
         make.centerX.centerY.equalToSuperview()
     }
     }
    
  3. 绑定数据

     extension SkyViewController: UITableViewDelegate, UITableViewDataSource {
     func numberOfSections(in tableView: UITableView) -> Int {
         return 1
     }
     
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return skyModel.daily?.count ?? 0
     }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "SkyCellID") as! SkyTableViewCell
         cell.displayData(sky: skyModel.daily![indexPath.row])
         return cell
         
     }
     
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return 60
     }
     
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         tableView.deselectRow(at: indexPath, animated: true)
     }
     }
    
  4. 自定义cell

     class SkyTableViewCell: UITableViewCell {
         override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
             super.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: reuseIdentifier)
     
     }
     
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
     
     func displayData(sky: Sky) {
         textLabel?.text = "湿度: \(sky.humidity ?? 0)  温度: \(sky.tempera ?? 0)  风速: \(sky.windSpeed ?? 0)"
         detailTextLabel?.text = "描述: \(sky.summary ?? "")"
    
     }
     }
    

相关文章

  • Moya+RxSwift展示天气数据

    RxSwift结合Moya获取天气数据,并结合tableView进行展示 效果图 一. cocoPod安装RxSw...

  • 微信天气小程序实例源码

    本项目主要实现了获取当前位置,从服务器请求天气数据展示在页面上,适合小程序初学者(ps:天气数据为虚拟数据) 安装...

  • 2019-06-17

    测试文本数据app/web展示共通测试文本数据app/web展示共通测试文本数据app/web展示共通测试文本数据...

  • python 观察者模式小demo

    目标:每一次天气数据变化的时候,主显示器更新数据,温度显示器只显示温度数据,并且把历史变化数据都展示出来。 思路:...

  • 前后端分离_分页

    在分页类编写数据,展示前端实现跳转 你的数据样式 前端接收数据,展示

  • App架构

    1.API 安全性 协议一致性 接口版本 2.业务数据展示 业务数据展示 展示主要是获取用户输入,或者展示数据 业...

  • 系统页面设计记录

    查询列表默认展示数据 vs 默认不展示数据。你认为那种更好?

  • mysql数据库sql语句创建数据库,创建数据表,修改表信息

    创建数据库 create database 数据库名称 展示数据库 show databases 展示数据表 s...

  • 性能监控学习随记

    Grafana:数据采集—》数据存储—》数据展示,grafana只是展示数据使用 所有的监控和系统都是在容器里面部...

  • 一个完整的Android应用程序(4)

    下面手动更新天气和切换城市 1. 手动更新天气由于在之前对天气进行了缓存,目前每次展示的都是之前的缓存数据,因此需...

网友评论

    本文标题:Moya+RxSwift展示天气数据

    本文链接:https://www.haomeiwen.com/subject/epewbxtx.html