CoinGecko APIを使って、1ビットコインの価格を取得するコードを書いたところ以下のエラーが発生。
2025-01-24 22:40:36.602294+0900 CryptoProfitCalculator[98674:10578595] Task <2A209DEB-C57F-4D13-AA05-23A45E20EC96>.<1> finished with error [-1003] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=-72000, NSUnderlyingError=0x600003b05530 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en3, ipv6, dns, expensive, _kCFStreamErrorCodeKey=-72000, _kCFStreamErrorDomainKey=10}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <2A209DEB-C57F-4D13-AA05-23A45E20EC96>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <2A209DEB-C57F-4D13-AA05-23A45E20EC96>.<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd, NSErrorFailingURLKey=https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd, _kCFStreamErrorDomainKey=10}
Error fetching data: A server with the specified hostname could not be found.
// APIからビットコイン価格を取得
private func fetchCryptoData() {
guard let url = URL(string: "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd") else {
print("Invalid URL")
return
}
let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
guard let self = self else { return }
if let error = error {
print("Error fetching data: \(error.localizedDescription)")
return
}
guard let data = data else {
print("No data received")
return
}
どうやら外部サーバとの接続時にエラーが発生しているようだ。
対処法は2つあり、1つ目は、Info.plistファイルにApp Transport Security Settingsを設定する。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>

AppTransportSecurity とは?
AppTransportSecurity(ATS)は、iOSおよびmacOSアプリでネットワーク通信のセキュリティを向上させるための仕組みです。
Appleは、すべてのアプリに対して、安全で暗号化された通信(HTTPS)を推奨しています。ATSは、以下のポリシーを強制することで安全性を確保します:
HTTPS を使用する。
サーバー証明書は信頼できるCA(認証局)によって発行されている必要がある。
暗号化強度が一定基準を満たしている必要がある。
NSAllowsArbitraryLoadsとは?
NSAllowsArbitraryLoads は NSAppTransportSecurity のサブキーで、ATSのポリシーを一時的に無効化するための設定です。
デフォルトの動作(ATS有効):
通信は原則として HTTPS(ポート443)を使用する必要がある。
HTTP通信(非暗号化通信)はデフォルトではブロックされる。
NSAllowsArbitraryLoads の設定:
<true/> に設定:
ATSのすべての制約が無効化され、HTTP通信やセキュリティ要件を満たさないHTTPS通信も許可される。
<false/>(または未指定):
デフォルトのATSポリシーが適用される。
2つ目は、Signing & Capabilities > App Sandbox > Network > Outgoing Connections(Client)にチェクをつける。
Outgoing Connections (Client) とは?
この設定は App Sandbox の機能の一部です。
App Sandbox は macOS や iOS アプリが動作する際のセキュリティ機構であり、アプリが外部リソースにアクセスする際に特定の権限が必要になります。
Outgoing Connections (Client):
アプリが外部のサーバーやAPIに接続する権限を許可する設定。
このチェックを入れると、アプリは外部ネットワークに対してリクエストを送信できるようになります(例: APIサーバーへのHTTPリクエスト)。
上記を設定後、実行で無事取得できました。
