【问题标题】:webAPI calls using swift使用 swift 调用 webAPI
【发布时间】:2019-11-27 04:26:56
【问题描述】:

我正在使用 GeoNames WebServices 处理 webAPI 调用,以查找给定城市和周边地区的地震信息。如何进行 webAPI 调用。到目前为止,我已经得到了地址的longitudelatitude。我很难理解我们如何获取信息。我想快速显示每个地球的datetimemagnitude

@IBAction func getAddress(_ sender: Any) {
    let addString = location.text
    CLGeocoder().geocodeAddressString(addString!, completionHandler:
    {(placemarks, error) in

        if error != nil {
            print("Geocode failed: \(error!.localizedDescription)")
        }else if placemarks!.count > 0{
            let placemark = placemarks![0]
            let location = placemark.location
            let coords = location!.coordinate

            self.lat = coords.latitude
            self.long = coords.longitude

            print(self.lat, "\n")
            print(self.long, "\n")
        }
        self.south = self.south + self.lat
        self.north = self.north + self.lat
        self.east = self.east + self.long
        self.west = self.west + self.long
        print("\n",self.north, "\n", self.south, "\n", self.east, "\n", self.west)
    })


    let urlAaString = "http://api.geonames.org/earthquakesJSON?north=" + String(self.north) +
    "&south=" + String(self.south) +
    "&east=" + String(self.east) +
    "&west=" + String(self.west) + "&username=demo"

    let url = NSURL(string: urlAaString)!
    let urlSession = URLSession.shared

    let jsonQuery = urlSession.dataTask(with: url as URL, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            print(error!.localizedDescription)
        }
        var err: NSError?


        let jsonResult = (try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary
        if (err != nil) {
            print("JSON Error \(err!.localizedDescription)")
        }

        print(jsonResult)

    })

    jsonQuery.resume()
}

【问题讨论】:

    标签: swift web geonames


    【解决方案1】:

    首先启用ATS,因为你使用的是http how I can enable ATS

    你可以使用alamofire alamofire

    就这么简单

     Alamofire.request("http://api.geonames.org/earthquakesJSON?north=" + String(self.north) +
    "&south=" + String(self.south) +
    "&east=" + String(self.east) +
    "&west=" + String(self.west) + "&username=demo") .responseJSON { response in
          //2.
          if let JSON = response.result.value{
             //3.
             self.jsonArray = JSON as? NSArray
             //4.
             for item in self.jsonArray! as! [NSDictionary]{
                //5.
                //you handle the json
             }
          }
          else
          {
             print("error with the data")
           }
       }
    

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2015-05-21
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多