facebook twitter hatena line google mixi email

Ios/swift/外部ライブラリ/Alamofire

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

Alamofireとは

httpに非同期でアクセスできるライブラリ

インストール

$ vi Podfile
platform :ios, '9.0'
target 'Helloworld' do
 use_frameworks!
 pod 'Alamofire', '~> 3.0'
end
$ pod install

使い方

import Alamofire
// json
       Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
           print(response.request)  // original URL request
           print(response.response) // URL response
           print(response.result)   // result of response serialization
           if let JSON = response.result.value {
               print("JSON: \(JSON)")
           }
           if response.result.isSuccess {
               let jsonDic = response.result.value as! NSDictionary
               let url = jsonDic["url"] as! String
               let headers = jsonDic["headers"] as! NSDictionary
               print(url);
               print(headers["Host"])
               for (key, value) in headers {
                   print(key)
                   print(value)
               }
           } else {
               let alert = UIAlertView(title: "エラー", message: "通信に失敗しました", delegate: self, cancelButtonTitle: "OK")
               alert.show()
           }
       }
// str
       Alamofire.request(.GET, "ttps://example.com/get", parameters: ["foo": "bar"]).responseString { response in
           if let str = response.result.value {
               print("str: \(str)")
           }
       }

参考:http://llcc.hatenablog.com/entry/2015/09/29/235112

画像API例

-php

$ret = array(
 'cnt' => 2,
 'imgs' => array(
   array(
     'thumbnail' => "https://pbs.twimg.com/media/ClupGSKWEAAeOuy.jpg",
     'name' => "オバマさん",
   ),
   array(
     'thumbnail' => "https://pbs.twimg.com/media/ClfZX4sWEAEeJzB.jpg",
     'name' => "ドロイド君",
   ),
 ),
);
echo json_encode($ret);
// 生成されたhtml
{"cnt":2,"imgs":[{"thumbnail":"https:\/\/pbs.twimg.com\/media\/ClupGSKWEAAeOuy.jpg","name":"\u30aa\u30d0\u30de\u3055\u3093"},{"thumbnail":"https:\/\/pbs.twimg.com\/media\/ClfZX4sWEAEeJzB.jpg","name":"\u30c9\u30ed\u30a4\u30c9\u541b"}]}

-ImgInit.swift

class ImgInit {
   var name:String = ""
   var thumbnail:String = ""
   init(name: String, thumbnail: String) {
       self.name = name
       self.thumbnail = thumbnail
   }
}

-SampleController.swift

Alamofire.request(.GET, "http://localhost/api/testimgs", parameters: ["param1": "value1"]).responseJSON { response in
   if response.result.isSuccess {
       let jsonDic = response.result.value as! NSDictionary
       let imgs = jsonDic["imgs"] as! NSArray
       let cnt = jsonDic["cnt"] as! Int
       print(cnt)
       var _imgs: Array<ImgInit> = []
       for img in imgs {
           let name:String = img["name"] as! String
           let thumbnail:String = img["thumbnail"] as! String
           let _img = ImgInit(name: name, thumbnail: thumbnail) as ImgInit
           _imgs.append(_img)
       }
       // こんな感じで取得
       for _img in _imgs {
           print("name=\(_img.name), thumbnail=\(_img.thumbnail)")
       }
   }
}

-出力

オバマさん
https://pbs.twimg.com/media/ClupGSKWEAAeOuy.jpg
ドロイド君
https://pbs.twimg.com/media/ClfZX4sWEAEeJzB.jpg

ローディング画面実装

-LoadingProxy.swift

import UIKit
struct LoadingProxy {
   static var myActivityIndicator: UIActivityIndicatorView!
   static func set(v:UIViewController){
       self.myActivityIndicator = UIActivityIndicatorView()
       self.myActivityIndicator.frame = CGRectMake(0, 0, 50, 50)
       self.myActivityIndicator.center = v.view.center
       self.myActivityIndicator.hidesWhenStopped = false
       self.myActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White
       self.myActivityIndicator.backgroundColor = UIColor.grayColor();
       self.myActivityIndicator.layer.masksToBounds = true
       self.myActivityIndicator.layer.cornerRadius = 5.0;
       self.myActivityIndicator.layer.opacity = 0.8;
       v.view.addSubview(self.myActivityIndicator);
       self.off();
   }
   static func on() {
       myActivityIndicator.startAnimating();
       myActivityIndicator.hidden = false;
   }
   static func off() {
       myActivityIndicator.stopAnimating();
       myActivityIndicator.hidden = true;
   }
   static func checkOn() -> Bool {
       if myActivityIndicator.hidden == true {
           return false;
       }
       return true
   }
}

-呼び出し元.swfit

// api処理前にon
LoadingProxy.set(self);
LoadingProxy.on();
// api処理後以下でoffにする
if LoadingProxy.checkOn() == true {
    LoadingProxy.off();
}

参考:http://swift-salaryman.com/uiactivityindicatorview.php