2016年8月24日水曜日

OpenWeatherMapでデータが取れない

基本無料で現在の天気情報、天気予報、過去の天気情報が取れるOpenWeatherMapというサービスがある。
無料のアカウントを取って使っていたのだが、しばらく確認してなかったらエラーが出て情報が取れなくなった。
変なエラー出た
アプリの方でエラーダイアログが出るとともに、Xcodeのログにも
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
と出た。

OpenWeatherMap側の問題?

調べると、以前はアカウントを特定するキーをコード中に埋め込んでも埋め込まなくても呼び出せたが、最近は埋め込まないといけなくなったということだが、これは以前から以下のように埋め込んでいた。

//openWeatherMapに緯度経度とAppIDを渡し、現在の気象情報のJSONを取る
NSString *url = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&cnt=1&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",coordinate.latitude ,coordinate.longitude];
NSData *json = [self correspondenceWithURL:url];

iOS側の問題だった

さらに調べたところ、iOS9からiOSのセキュリティが厳しくなり、App Transport Security(ATS)という機能によって、これが有効な場合にはウェブサービス間でHTTPの通信ができないのだそうだ。
対応は上記のエラーメッセージにも書かれているが、アプリのInfo.plistの辞書に例外サイトを指定してやらないといけない。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>api.openweathermap.org</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

Open as Source codeで表示した場合

うまくいっただよ

うまくいきました🎵

0 件のコメント:

コメントを投稿