facebook twitter hatena line email

「Ios/swift/外部ライブラリ/Alamofire」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
 
(同じ利用者による、間の12版が非表示)
行14: 行14:
 
==使い方==
 
==使い方==
 
  import Alamofire
 
  import Alamofire
         Alamofire.request(.GET, "https://twitter.com")
+
// json
            .responseJSON { response in
+
         Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
                print(response.request)
+
            print(response.request) // original URL request
                 print(response.response)
+
            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
  Optional(<NSMutableURLRequest: 0x15de5ce90> { URL: https://twitter.com })
+
 
  Optional(<NSHTTPURLResponse: 0x15de03170> { URL: https://twitter.com/ } { status code: 200, headers {
+
==画像API例==
    "Cache-Control" = "no-cache, no-store, must-revalidate, pre-check=0, post-check=0";
+
-php
    "Content-Encoding" = gzip;
+
  $ret = array(
    "Content-Length" = 32873;
+
  'cnt' => 2,
     "Content-Type" = "text/html;charset=utf-8";
+
  'imgs' => array(
     Date = "Thu, 23 Jun 2016 03:08:19 GMT";
+
    array(
     Expires = "Tue, 31 Mar 1981 05:00:00 GMT";
+
      'thumbnail' => "https://pbs.twimg.com/media/ClupGSKWEAAeOuy.jpg",
     "Last-Modified" = "Thu, 23 Jun 2016 03:08:19 GMT";
+
      'name' => "オバマさん",
     Pragma = "no-cache";
+
    ),
    Server = "tsa_a";
+
    array(
    "Set-Cookie" = "fm=0; Expires=Thu, 23 Jun 2016 03:08:09 GMT; Path=/; Domain=.twitter.com; Secure; HTTPOnly, _twitter_sess=BAh7CSIKZmxhc2hJQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCAHToMY3NyZl9p%250AZCIlZGMzNTBjMWZiMGI5MmZlNmM1MDVmMmMyNTNjZDVjYjM6B2lkIiU0MzA2%250AN2ZiMDgzYWY4YTYyYTk5YTdiYjRmNQ%253D%253D--49410ad03124cde2eab339902b9f116860f4; Path=/; Domain=.twitter.com; Secure; HTTPOnly, guest_id=v1%3A146658349991; Domain=.twitter.com; Path=/; Expires=Sat, 23-Jun-2018 03:08:19 UTC";
+
      'thumbnail' => "https://pbs.twimg.com/media/ClfZX4sWEAEeJzB.jpg",
     Status = "200 OK";
+
      'name' => "ドロイド君",
    "Strict-Transport-Security" = "max-age=631138519";
+
    ),
    "x-connection-hash" = a80a35cb815d23f423a94ea3bb30;
+
  ),
    "x-content-type-options" = nosniff;
+
  );
    "x-frame-options" = SAMEORIGIN;
+
echo json_encode($ret);
    "x-response-time" = 157;
+
// 生成されたhtml
     "x-transaction" = 00d8e8bec4f0;
+
{"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"}]}
     "x-twitter-response-tags" = BouncerCompliant;
+
 
     "x-ua-compatible" = "IE=edge,chrome=1";
+
-ImgInit.swift
     "x-xss-protection" = "1; mode=block";
+
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

2016年7月27日 (水) 23:08時点における最新版

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