LoginSignup
0
1

More than 1 year has passed since last update.

swiftでAPIを実装

Posted at

APIを実装するには以下の手順を行います

変数urlにURLデータを入れる → そこからデータを取得する → そのデータをJSON解析して欲しいデータを返す

具体的にコードで見て行きましょう。
以下はBitcoinのデータを受け取り1Bitcoinが何円、何ドル、、、なのかを返す関数です。
ここでは具体的なapiの取得は割愛します。

具体的なコード


func getCoinPrice(for currency: String){
        let urlString = "\(baseURL)/\(currency)?apikey=\(apiKey)"

        if let url = URL(string: urlString){
            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url){ (data, response, error) in
                if error != nil{
                    print(error!)
                    return
                }

                if let safeData = data{

                    if let bitcoinPrice = self.parseJSON(safeData){

                        let priceString = String(format: "%.2f", bitcoinPrice)
                        self.delegate?.didUpdatePrice(price: priceString, currency: currency)
                    }
                }
            }
            task.resume()
        }

上のコードはurlに取得したURLを入れ、URLSession関数を使用しデータ処理群をまとめ、dataTaskを用いてURLを使用したtask変数を作ります。その時クロージャーを用いてデータを取得する処理を書いています。データが存在するかどうかで場合分けをしており、存在していた場合parseJSON関数に入れJSONデータを解析します。以下がparseJSON関数です。

 func parseJSON(_ data: Data) -> Double? {
        let decoder = JSONDecoder()
        do{
            let decodedData = try decoder.decode(CoinData.self, from: data)
            let lastPrice = decodedData.rate
            return lastPrice

        } catch {
            delegate?.didFailWithError(error: error)
            return nil
        }
    }

data型のdataを受け取りJSONDecoderを使用することで解析しています。尚、「let decodedData = try decoder.decode(CoinData.self, from: data)」のように解析する際の第一引数として構造体を別ファイルで作っておりそこに当てはめています。

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1