Last active
November 16, 2017 15:59
-
-
Save takashi1975/dbb6a51467de70cde25890d58e8c595d to your computer and use it in GitHub Desktop.
Swift4 標高API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//呼び出し側の記述例 | |
//WebAPI | |
let webApi = Geospatial() | |
webApi.getElevation(coordinate, closure: { (json) in | |
if let elevation = json?.elevation { | |
print(elevation) | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreLocation | |
class Geospatial: NSObject { | |
//JSON 全体の構成 | |
struct Json: Codable { | |
let elevation: Double | |
let hsrc: String | |
} | |
} | |
// MARK: - | |
extension Geospatial { | |
//Web 問い合わせ | |
public func getElevation(_ coordinate: CLLocationCoordinate2D?, closure:@escaping (_ json: Json?)->()) { | |
//前提条件 | |
guard let coordinate = coordinate else { | |
return | |
} | |
let url_text = String(format:"https://cyberjapandata2.gsi.go.jp/general/dem/scripts/getelevation.php?lat=%f&lon=%f&outtype=JSON", coordinate.latitude, coordinate.longitude) | |
if let url = URL(string: url_text) { | |
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, responce, error) in | |
//前提条件 | |
if let error = error { | |
print(error) | |
return | |
} | |
//Jsonをパース | |
let json = self.decode(data) | |
//*** callback *** | |
DispatchQueue.main.async() { | |
closure(json) | |
} | |
}) | |
task.resume() | |
} | |
} | |
//JSONデータの読み込み | |
private func decode(_ json: Data?) -> Json? { | |
//前提条件 | |
guard let json = json else { | |
return nil | |
} | |
//データ読み込み | |
let decoder = JSONDecoder() | |
if let data = try? decoder.decode(Json.self, from: json) { | |
//正常終了 | |
return data | |
} | |
//異常終了 | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment