LoginSignup
5
4

More than 5 years have passed since last update.

ベーシック認証とJSONとUIwebView。

Posted at

ベーシック認証が設定されているサーバーのJSONを読み込んでやりたかった事。
① 画像までのパスを取得してUIImageに設定したかった。
② UIWebViewに読み込みたいページのURLを取得して表示したかった。

で、、、
JSONに関してはAlamofireを使ってJSONを取得

JSON
{
  "responseData": {
    "feed": {
      "entries": [
        {
          "id": "220",
          "title": "タイトルが入ります。",
          "text": "記事の本文です。",
          "cat": "カテゴリー",
          "subCat": "サブカテゴリー",
          "thumbnail": "http://◯◯◯.com/img/entry/☓☓☓.jpg",
          "url": "http://◯◯◯.com/△△△△.html"
        }
      ]
    }
  }
}

というJSONデータを読み込みます。

Swift
let user = "userId"
let password = "userPass"

// JSONのパース
func parse(url: String, completion: (([JSON]?, NSError?) -> Void)){
   var url = NSURL(string: url)
   Alamofire.request(.GET, url!, parameters: nil, encoding: .JSON)
      .authenticate(user: user, password: password)
      .responseJSON{ (request, response, data, error) in
         let json = JSON(data!)
         let entries = json["responseData"]["feed"]["entries"].array
            completion(entries, error)
   }
}

.authenticate(user: user, password: password)
と、この一文を足すとベーシック認証下のJSONは読み込めましたが、画像、UIWebViewへの埋め込みはできませんでした。

色々と考えたのですが結局JSONファイルを修正しました。

JSON
{
  "responseData": {
    "feed": {
      "entries": [
        {
          "id": "220",
          "title": "タイトルが入ります。",
          "text": "記事の本文です。",
          "cat": "カテゴリー",
          "subCat": "サブカテゴリー",
          "thumbnail": "http://userId:userPass@◯◯◯.com/img/entry/☓☓☓.jpg",
          "url": "http://userId:userPass@◯◯◯.com/△△△△.html"
        }
      ]
    }
  }
}

てな感じで、URLに直接ユーザー名・パスワードを埋め込みました。
(このページを参照)
http://qiita.com/ngkazu/items/6da021edf177f40e1f26

これで無事、表示しました。
開発中のアプリ内のJSONキャッシュは結構きついのでキャッシュ対策をしておく方が無難です。

http://◯◯◯.com/▲▲▲▲▲.json?123

とURLに?〜をつければOK。

5
4
0

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
5
4