ios - 如何正确返回 JSON 短语的函数?

标签 ios arrays json swift

最近我开始了一个使用CityBikes API的项目,它可以实时获取世界上不同城市的自行车共享站的数据( https://api.citybik.es/v2/ )。 作为第一步,我提取了各种链接以获取接收各种信息所需的数据。 然后我创建了一个函数 extractStationData,它获取链接并将它们添加到“基本”链接中,从而允许解析 JSON 并接收各种数据。我的问题就出现在这一点上,因为我无法通过该函数将之前获得的数据添加到链接中。 我怎样才能做到这一点?我必须更改带有返回值的函数吗?

代码如下:

    let networksURL = "https://api.citybik.es/v2/networks/"
    guard let dataURL = URL(string: networksURL) else {return}

    URLSession.shared.dataTask(with: dataURL) { (data, response, err) in

        guard let data = data else {return}
        let dataAsString = String(data: data, encoding: .utf8)

    guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
        print("Error: Couldn't decode data")
        return
    }

    print("Networks link:")
    for article in blog.articles {
        print("- \(article.href)")
    }

        func extractStationData() {
            for article in blog.articles {
                article.href
            }
        }

        let stationDataURL = "https://api.citybik.es\(extractStationData())"
        guard let newDataURL = URL(string: stationDataURL) else {return}

        URLSession.shared.dataTask(with: newDataURL) { (data, response, err) in

            guard let data = data else {return}
            let dataAsStringForStation = String(data: data, encoding: .utf8)

            guard let dataFromStation = try? JSONDecoder().decode(Datamain.self, from: data) else {
                print("Error: Couldn't decode station data")
                return
            }

            print("data:")
            for something in dataFromStation.qwerty {
                print("- \(something.empty_slots)")
                print("- \(something.free_bikes)")
                print("- \(something.name)")
                print("- \(something.latitude)")
                print("- \(something.longitude)")

            }

            }.resume()
}.resume()

最佳答案

您的代码无法运行。

您必须将这两个任务分开,并使用 DispatchGroup 在第二个任务中的网络请求完成时收到通知。

首先使用完成处理程序为主任务创建一个函数,我省略了大部分代码来显示工作流程

func getMainData(completion: @escaping(Blog)->Void) {

  ...
  URLSession.shared.dataTask(with: dataURL) { (data, response, err) in 
     ...
     completion(blog)
  }

}

根据完成处理程序中的主要数据调用该函数并执行网络请求

getMainData() { blog in 
    let group = DispatchGroup()
    for article in blog.articles {
        ...
        group.enter()
        // create newDataURL from article
        URLSession.shared.dataTask(with: newDataURL) { (data, response, err) in
           ...
            for something in dataFromStation.qwerty {
               print("- \(something.empty_slots)")
               print(" .... "
            }
            group.leave()
        }

    }
    group.notify(queue: DispatchQueue.main) {
        print("finished")
    }

}

但是,我建议(仅)在主视图 Controller 中加载主要数据,并在详细 View Controller 中按需加载所选位置的数据。

关于ios - 如何正确返回 JSON 短语的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52917475/

相关文章:

ios - glReadPixels直接贴图

ios - 授权 HealthKit 时出错 - Code=100 "Rolling back the health database is unsupported."

c++ - 在 C++ 中创建指针数组的 char* 和 int* 数据​​类型有什么区别?

javascript - JSON 无法正确呈现

ios - 谷歌地图 : How to draw dash line to connect with starting point of direction path on google map ios

ios - 如何让 AVCaptureSession 和 AVPlayer 尊重 AVAudioSessionCategoryAmbient?

c# - 如何从数组创建字典

c - 使用指针更改函数中数组值的问题

json - Git,Xcode 7 中 Content.json 文件中的树冲突

php - 在 JQuery 中解析 JSON 并设置输入