iOS 开发,Mock 服务器接口

背景: 后端工程师有时候忙,不能给前端工程师准备合适的开发数据,前端

这个时候,就须要 Mock Server 了json

分两步,后端

  • 获取数据,根据本身的需求,修改数据
  • 提供数据

第一步,获取数据

根据本身开发的需求修改api

先把接口请求到的 JSON 落库,网络

// json 转 plist, 放在沙盒的 Document 目录下

        do{
            let json = try JSONSerialization.jsonObject(with: self, options: JSONSerialization.ReadingOptions())
            if let dict = json as? [String: Any]{
                let src = dict as NSDictionary
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let path = documentsURL.appendingPathComponent("one.plist")
                let result = src.write(to: path, atomically: true)
                print(result)
            }
        }
        catch let error{
            print("gg 了, \(error)")
        }

若是是直接跑模拟器,打印路径,直接就能够找到 plist .前端工程师

直接跑真机,能够经过 Woodpecker, 同步文件到 Mac 上。app

Screen Shot 2019-12-13 at 2.15.56 PM.png


第二步,提供数据

先要把下载获取到的 json 文件,添加在 project 里面,atom

run 的时候,就打在 Bundle 里面了url

func request(_ callback: @escaping (GeneralSingle<PracticeList>) -> Void){
        
        
        let debug = true
        guard debug == false else {
        
        // 新的接口请求逻辑,走本地的,包含在 Bundle 里面的 plist 文件
            do{
                if let path = Bundle.main.url(forResource: "one", withExtension: "plist"){
                    let data = try Data(contentsOf: path)
                    let decoder = PropertyListDecoder()
                    let info = try decoder.decode(GeneralSingle<PracticeList>.self, from: data)
                    callback(info)
                }
            }
            catch let error as NSError{
                print(error)
            }
            return
        }
        
        
        
        // 原来逻辑,走网络请求
        AF.request(RequsetURL.youOwn, method: .get, headers: AF.bearer).response { (resp) in
         // ...
相关文章
相关标签/搜索