主に備忘録

基本的には自分用の備忘録っぽいもの。

MacにVagrantでCentOS+FuelPHPの環境を作成する(その4(おまけ). ローカルのFuelPHPを使う)

CentOS側でFuelPHPをダウンロード(インストール)すると編集するのが面倒なので、ローカルに用意したFuelPHPを使う
ディレクトリ構成等はその3で作成したものをベースにする

実施環境

今回のゴール

ローカルのFuelPHPに加えた変更がVagrant側に反映される

今回の成果物

こちらに置いてあります

negibouze/vagrant-fuelphp_part4

1. ローカルにFuelPHPを用意する

今回は公式サイトからダウンロードしたzipをVagrantfileと同じ階層に展開
また、ディレクトリ名を「fuelphp-1.7.3」から「fuelphp」に変更

2. Vagrantfileを編集する

step1. ローカルのFuelPHPを同期させる

下記2行を追加

host.vm.synced_folder ".", "/vagrant"
host.vm.synced_folder "./fuelphp", "/srv/example/fuelphp", mount_options: ['dmode=777','fmode=666']

編集前

Vagrant.configure(2) do |config|

  config.vm.box = "puppetlabs/centos-6.6-64-nocm"
  config.vm.box_url = "https://vagrantcloud.com/puppetlabs/boxes/centos-6.6-64-nocm/versions/1.0.2/providers/virtualbox.box"

  config.vm.define :"web1" do |host|
    host.vm.hostname = "web1"
    host.vm.network :private_network, ip: "192.168.100.11", netmask: "255.255.255.0"
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/site.yml"
    ansible.inventory_path = "provisioning/hosts"
    ansible.limit = 'all'
  end
end

編集後

Vagrant.configure(2) do |config|

  config.vm.box = "puppetlabs/centos-6.6-64-nocm"
  config.vm.box_url = "https://vagrantcloud.com/puppetlabs/boxes/centos-6.6-64-nocm/versions/1.0.2/providers/virtualbox.box"

  config.vm.define :"web1" do |host|
    host.vm.hostname = "web1"
    host.vm.network :private_network, ip: "192.168.100.11", netmask: "255.255.255.0"
    host.vm.synced_folder ".", "/vagrant"
    host.vm.synced_folder "./fuelphp", "/srv/example/fuelphp", mount_options: ['dmode=777','fmode=666']
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/site.yml"
    ansible.inventory_path = "provisioning/hosts"
    ansible.limit = 'all'
  end
end

3. AnsibleのPlaybookを編集する

step1. webtier/tasks/fuelphp.ymlの編集

  • FuelPHPのダウンロード、および解凍は不要なので削除
  • example/fuelphpの存在有無によるチェックは使えないので削除

編集前

---
# install FuelPHP
- stat: path=/usr/local/src/fuelphp-1.7.3.zip
  register: fuelphp_zip
- name: download fuelphp1.7.3
  get_url: url=http://fuelphp.com/files/download/34 dest=/usr/local/src/fuelphp-1.7.3.zip
  when: not fuelphp_zip.stat.exists
- stat: path=/srv/example/fuelphp
  register: fuelphp
- name: create target directory
  command: mkdir -p /srv/example
- name: unzip fuelphp
  command: unzip -o /usr/local/src/fuelphp-1.7.3.zip -d /srv/example
  when: not fuelphp.stat.exists
- name: rename unzip directory
  command: mv fuelphp-1.7.3 fuelphp
  args:
    chdir: /srv/example/
  when: not fuelphp.stat.exists
- name: install oil
  shell: get.fuelphp.com/oil | sh
  when: not fuelphp.stat.exists
- name: refine install
  command: php oil refine install
  args:
    chdir: /srv/example/fuelphp
  notify: restart httpd
  when: not fuelphp.stat.exists

編集後

---
# install FuelPHP
- name: create target directory
  command: mkdir -p /srv/example
- name: install oil
  shell: get.fuelphp.com/oil | sh
- name: refine install
  command: php oil refine install
  args:
    chdir: /srv/example/fuelphp
  notify: restart httpd

4. 動作確認

step1. 仮想マシンを作成する

$ vagrant up

step2. 動作確認(編集前)

ブラウザで「192.168.100.11」を開いて下記画面が表示されればOK
f:id:ita3y:20151123194535p:plain

step3. ローカルのFuelPHPを編集する

試しにfuelphp/fuel/app/views/welcome/index.phpを適当に編集

編集前

<div class="jumbotron">
  <h1>Welcome!</h1>
  <p>You have successfully installed the FuelPHP Framework.</p>
  <p><a class="btn btn-primary btn-lg" href="http://docs.fuelphp.com">Read the Docs</a></p>
</div>

編集後

<div class="jumbotron">
  <h1>ようこそ!</h1>
  <p>あなたはFuelPHPフレームワークのインストールに成功しました。</p>
  <p><a class="btn btn-primary btn-lg" href="http://docs.fuelphp.com">ドキュメントを読む</a></p>
</div>

step4. 動作確認(編集後)

ブラウザを更新して下記画面が表示されればOK f:id:ita3y:20151128000540p:plain

MacにVagrantでCentOS+FuelPHPの環境を作成する(その3. AnsibleのPlaybookを分割してディレクトリ構成も変えてみる)

その2で作成したPlaybookを分割してディレクトリ構成も変えてみる

実施環境

目標

Ansible + Vagrantを使用して下記環境を構築する

今回のゴール

vagrant upだけでFuelPHPのWelcomeが表示できるようにする

今回の成果物

こちらに置いてあります

negibouze/vagrant-fuelphp_part3

1. 各ツールの準備(インストール済みの場合不要)

step1. Homebrewをインストールする

(省略)

step2. Homebrew Caskをインストールする

(省略)

step3. VirtualBoxをインストールする

(省略)

step4. Vagrantをインストールする

(省略)

step5. Vagrant-vbguest pluginをインストールする

(省略)

step6. Ansibleをインストールする

(省略)

2. Ansibleのディレクトリ構成変更

step1. ベストプラクティスを参考にディレクトリとファイルを作成する(最終的に今回は使わなかったディレクトリもあります)

roles/
   hosts
   site.yml
   apservers.yml
   common/
      files/
      handlers/
         main.yml
      tasks/
         main.yml
   webtier/
      files/
         httpd.conf
         php.ini
      handlers/
         main.yml
      tasks/
         curl.yml
         fuelphp.yml
         git.yml
         httpd.yml
         main.yml
         php.yml   

3. AnsibleのPlaybookの記述を分割する

step1. site.ymlの編集

---
- include: apservers.yml

step2. apservers.ymlの編集

---
- hosts: apservers
  sudo: true
  user: vagrant
  roles:
    - common
    - webtier

step3. common/tasks/main.ymlの編集

---
- name: change timezone
  command: cp -p /usr/share/zoneinfo/Japan /etc/localtime
- name: remove all rules from iptables
  command: /sbin/iptables -F
- name: iptables stop
  command: /sbin/service iptables stop
- name: iptables off
  command: /sbin/chkconfig iptables off

step4. webtier/handlers/main.ymlの編集

---
- name: copy httpd.conf
  copy: src=../files/httpd.conf dest=/etc/httpd/conf/httpd.conf
- name: enable httpd launch settings
  command: /sbin/chkconfig httpd on
- name: copy php.ini
  copy: src=../files/php.ini dest=/etc/php.ini
- name: restart httpd
  service: name=httpd state=restarted

step5. webtier/tasks/main.ymlの編集

今回はgitとcurlは不要だったのでコメントアウト(せっかくなので.ymlは作成しています)

---
- include: httpd.yml
# - include: git.yml
- include: php.yml
# - include: curl.yml
- include: fuelphp.yml

step6. webtier/tasks/配下(main.yml以外)の編集

httpd.yml

---
- name: install httpd
  yum: name=httpd state=present
  notify:
    - copy httpd.conf
    - enable httpd launch settings

git.yml

---
- name: install dependency packages
  yum: pkg={{item}} state=present
  with_items:
    - curl-devel
    - expat-devel
    - gettext-devel
    - openssl-devel
    - zlib-devel
    - perl-ExtUtils-MakeMaker
- stat: path=/usr/local/src/git
  register: git_repo
- name: temporary install old version git
  yum: name=git state=present
  when: not git_repo.stat.exists
- name: clone(or pull) latest version git
  git: repo=https://git.kernel.org/pub/scm/git/git.git dest=/usr/local/src/git
- name: remove old git
  yum: name=git state=absent
  when: not git_repo.stat.exists
- name: compile git
  shell: "{{ item }}"
  args:
    chdir: /usr/local/src/git
  with_items:
    - make prefix=/usr/local all
    - make prefix=/usr/local install

php.yml

---
- name: install epel
  yum: name=http://ftp.iij.ad.jp/pub/linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm state=present
- name: install remi
  yum: name=http://rpms.famillecollet.com/enterprise/remi-release-6.rpm state=present
- name: install php & packages (& dependencies)
  yum: pkg={{item}} state=present enablerepo=remi,remi-php56
  with_items:
    - php
    - php-common
    - php-cli
  notify: copy php.ini

curl.yml

---
- name: install latest version curl
  yum: pkg={{item}} state=present
  with_items:
    - http://www.city-fan.org/ftp/contrib/yum-repo/city-fan.org-release-1-13.rhel6.noarch.rpm
    - libcurl

fuelphp.yml

---
- stat: path=/usr/local/src/fuelphp-1.7.3.zip
  register: fuelphp_zip
- name: download fuelphp1.7.3
  get_url: url=http://fuelphp.com/files/download/34 dest=/usr/local/src/fuelphp-1.7.3.zip
  when: not fuelphp_zip.stat.exists
- stat: path=/srv/example/fuelphp
  register: fuelphp
- name: create target directory
  command: mkdir -p /srv/example
- name: unzip fuelphp
  command: unzip -o /usr/local/src/fuelphp-1.7.3.zip -d /srv/example
  when: not fuelphp.stat.exists
- name: rename unzip directory
  command: mv fuelphp-1.7.3 fuelphp
  args:
    chdir: /srv/example/
  when: not fuelphp.stat.exists
- name: install oil
  shell: get.fuelphp.com/oil | sh
  when: not fuelphp.stat.exists
- name: refine install
  command: php oil refine install
  args:
    chdir: /srv/example/fuelphp
  notify: restart httpd
  when: not fuelphp.stat.exists

4. 動作確認

step1. 仮想マシンを作成する

$ vagrant up

step2. 動作確認

ブラウザで「192.168.100.11」を開いて下記画面が表示されればOK
f:id:ita3y:20151123194535p:plain

5. ちょっとした感想

webtier/tasksの配下が分割しすぎな気もしますが、インストール有無をmain.ymlコメントアウトで制御できるのは良いかもしれません

6. 参考にしたサイト

実践!Ansibleベストプラクティス(前編) - さくらのナレッジ
Ansibleを使い出す前に押さえておきたかったディレクトリ構成のベストプラクティス - 双六工場日誌

MacにVagrantでCentOS+FuelPHPの環境を作成する(その2. Ansibleを使ってみる)

その1で作成したshellをAnsibleに変えてみる

実施環境

目標

Ansible + Vagrantを使用して下記環境を構築する

今回のゴール

vagrant upだけでFuelPHPのWelcomeが表示できるようにする

今回の成果物

こちらに置いてあります

negibouze/vagrant-fuelphp_part2

1. 各ツールの準備(インストール済みの場合不要)

step1. Homebrewをインストールする

(省略)

step2. Homebrew Caskをインストールする

(省略)

step3. VirtualBoxをインストールする

(省略)

step4. Vagrantをインストールする

(省略)

step5. Vagrant-vbguest pluginをインストールする

(省略)

step6. Ansibleをインストールする

$ brew install ansible

2. Vagrantfileの編集

step1. $scriptを削除

下記は不要になるため削除

$script = <<SCRIPT
  # 中略
SCRIPT

step2. provisionを編集

config.vm.provision "ansible" do |ansible|
  ansible.playbook = "provisioning/site.yml"
  ansible.inventory_path = "provisioning/hosts"
  ansible.limit = 'all'
end

ここまででこんな感じ

Vagrant.configure(2) do |config|

  config.vm.box = "puppetlabs/centos-6.6-64-nocm"
  config.vm.box_url = "https://vagrantcloud.com/puppetlabs/boxes/centos-6.6-64-nocm/versions/1.0.2/providers/virtualbox.box"

  config.vm.define :"web1" do |host|
    host.vm.hostname = "web1"
    host.vm.network :private_network, ip: "192.168.100.11", netmask: "255.255.255.0"
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/site.yml"
    ansible.inventory_path = "provisioning/hosts"
    ansible.limit = 'all'
  end
end

3. Ansibleのファイルを作成

step1. Ansible用のディレクトリ作成(任意)

$ mkdir provisioning && cd $_

step2. inventory fileを作成

$ touch hosts

step3. Playbookを作成

$ touch site.yml

4. hostsを編集する

step1. 対象サーバのIPアドレスを追加

[server]
192.168.100.11

5. Playbookを編集する

その1で記述したshellの内容をYAMLに書き換える

step1. 書き始め

---
- hosts: server
  sudo: true
  user: vagrant
  tasks:
  handlers:

step2. Timezoneを変更

- name: change timezone
  command: cp -p /usr/share/zoneinfo/Japan /etc/localtime

step3. iptablesを無効にする

- name: remove all rules from iptables
  command: /sbin/iptables -F
- name: iptables stop
  command: /sbin/service iptables stop
- name: iptables off
  command: /sbin/chkconfig iptables off

step4. httpd(apache)をインストールする

notifyを使用してhttpd.confをコピーと起動設定を行う

tasks

- name: install httpd
  yum: name=httpd state=present
  notify:
    - copy httpd.conf
    - enable launch settings

handlers

  - name: copy httpd.conf
    copy: src=../httpd.conf dest=/etc/httpd/conf/httpd.conf
  - name: enable launch settings
    command: /sbin/chkconfig httpd on

step5. Gitをインストールする(やらなくても良い)

FuelPHPをgitで持ってくるのをやめたためこの手順は不要でした(ここは時間がかかるのでやらない方が良いです)
* 多少古くても良い場合

- name: install old version git
  yum: name=git state=present
  • 最新版を入れる場合
- name: install dependency packages
  yum: pkg={{item}} state=present
  with_items:
    - curl-devel
    - expat-devel
    - gettext-devel
    - openssl-devel
    - zlib-devel
    - perl-ExtUtils-MakeMaker
- stat: path=/usr/local/src/git
  register: git_repo
- name: temporary install old version git
  yum: name=git state=present
  when: not git_repo.stat.exists
- name: clone(or pull) latest version git
  git: repo=https://git.kernel.org/pub/scm/git/git.git dest=/usr/local/src/git
- name: remove old git
  yum: name=git state=absent
  when: not git_repo.stat.exists
- name: compile git
  shell: "{{ item }}"
  args:
    chdir: /usr/local/src/git
  with_items:
    - make prefix=/usr/local all
    - make prefix=/usr/local install

step6. PHP5.6をインストールする

notifyを使用してphp.iniをコピーする

tasks

- name: install epel
  yum: name=http://ftp.iij.ad.jp/pub/linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm state=present
- name: install remi
  yum: name=http://rpms.famillecollet.com/enterprise/remi-release-6.rpm state=present
- name: install php & packages (& dependencies)
  yum: pkg={{item}} state=present enablerepo=remi,remi-php56
  with_items:
    - php
    - php-common
    - php-cli
  notify: copy php.ini

handlers

- name: copy php.ini
  copy: src=../php.ini dest=/etc/php.ini

step7. curlを更新する(やらなくても良い)

- name: install latest version curl
  yum: pkg={{item}} state=present
  with_items:
    - http://www.city-fan.org/ftp/contrib/yum-repo/city-fan.org-release-1-13.rhel6.noarch.rpm
    - libcurl

step8. FuelPHPをインストールする

$ oil create <project_name>

tasks

- stat: path=/usr/local/src/fuelphp-1.7.3.zip
  register: fuelphp_zip
- name: download fuelphp1.7.3
  get_url: url=http://fuelphp.com/files/download/34 dest=/usr/local/src/fuelphp-1.7.3.zip
  when: not fuelphp_zip.stat.exists
- stat: path=/srv/example/fuelphp
  register: fuelphp
- name: create target directory
  command: mkdir -p /srv/example
- name: unzip fuelphp
  command: unzip -o /usr/local/src/fuelphp-1.7.3.zip -d /srv/example
  when: not fuelphp.stat.exists
- name: rename unzip directory
  command: mv fuelphp-1.7.3 fuelphp
  args:
    chdir: /srv/example/
  when: not fuelphp.stat.exists
- name: install oil
  shell: get.fuelphp.com/oil | sh
- name: refine install
  command: php oil refine install
  args:
    chdir: /srv/example/fuelphp
  notify: restart httpd

handlers

- name: restart httpd
  service: name=httpd state=restarted

6. 動作確認

step1. 仮想マシンを作成する

$ vagrant up

step2. 動作確認

ブラウザで「192.168.100.11」を開いて下記画面が表示されればOK
f:id:ita3y:20151123194535p:plain

MacにVagrantでCentOS+FuelPHPの環境を作成する(その1. Vagrantfile(shell)で頑張る)

実施環境

目標

Vagrantを使用して下記環境を構築する

今回のゴール

vagrant upだけでFuelPHPのWelcomeが表示できるようにする

今回の成果物

こちらに置いてあります

negibouze/vagrant-fuelphp_part1

1. 各ツールの準備(インストール済みの場合不要)

step1. Homebrewをインストールする

ターミナルで下記を実行

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

step2. Homebrew Caskをインストールする

$ brew install caskroom/cask/brew-cask

step3. VirtualBoxをインストールする

$ brew cask install virtualbox

step4. Vagrantをインストールする

$ brew cask install vagrant

step5. Vagrant-vbguest pluginをインストールする

$ vagrant plugin install vagrant-vbguest

2. Vagrantfileの作成

step1. 対象ディレクトリ配下で下記を実行

$ vagrant init

3. Vagrantfileの編集

step1. vm.boxを設定

今回はpuppetlabsのCentOS 6.6(64-bit)を使用
!Puppetは使わないので「nocm」

config.vm.box = "puppetlabs/centos-6.6-64-nocm"
# boxがない場合、インストール
config.vm.box_url = "https://vagrantcloud.com/puppetlabs/boxes/centos-6.6-64-nocm/versions/1.0.2/providers/virtualbox.box"

step2. $scriptを追記

$script = <<SCRIPT
  # 詳細は後で追加
SCRIPT

step3. provisionを追記

config.vm.provision "shell", inline: $script

ここまででこんな感じ

$script = <<SCRIPT
 # 詳細は後で追加
SCRIPT

Vagrant.configure(2) do |config|

  config.vm.box = "puppetlabs/centos-6.6-64-nocm"
  config.vm.box_url = "https://vagrantcloud.com/puppetlabs/boxes/centos-6.6-64-nocm/versions/1.0.2/providers/virtualbox.box"

  config.vm.define :"web1" do |host|
    host.vm.hostname = "web1"
    host.vm.network :private_network, ip: "192.168.100.11", netmask: "255.255.255.0"
  end

  config.vm.provision "shell", inline: $script
end

4. $scriptに処理を追加

step1. Timezoneを変更

# timezone
cp -p /usr/share/zoneinfo/Japan /etc/localtime

step2. iptablesを無効にする

# remove all rules
/sbin/iptables -F
# iptables stop
/sbin/service iptables stop
# iptables off
/sbin/chkconfig iptables off

step3. httpd(apache)をインストールする

httpd.confは事前に用意しておく
!DocumentRoot とか編集しています

### apache install ###
# install httpd
yum install -y httpd
# cp local httpd.conf
cp -a /vagrant/httpd.conf /etc/httpd/conf/
# httpd restart
/sbin/service httpd restart
# enable launch settings
/sbin/chkconfig httpd on

step4. Gitをインストールする(やらなくても良い)

FuelPHPをgitで持ってくるのをやめたためこの手順は不要でした(ここは時間がかかるのでやらない方が良いです)
* 多少古くても良い場合

yum install -y git
  • 最新版を入れる場合
### git install ###
# install dependency packages (temporariy install old version git)
yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel perl-ExtUtils-MakeMaker git
cd /usr/local/src/
# download latest version
git clone https://git.kernel.org/pub/scm/git/git.git
# remove old version
sudo yum remove -y git
cd git
# make
make prefix=/usr/local all
make prefix=/usr/local install

step5. PHP5.6をインストールする

### php5.6 install ###
# install epel & remi
sudo rpm -Uvh http://ftp.iij.ad.jp/pub/linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
# install php & packages (& dependencies)
sudo yum install -y --enablerepo=remi --enablerepo=remi-php56 php php-common php-cli

step6. php.iniをコピーする

php.iniは事前に用意しておく
!date.timezone とか編集しています

# cp local php.ini
cp -a /vagrant/php.ini /etc/

step7. curlを更新する(やらなくても良い)

### ref: update curl ###
sudo rpm -Uvh http://www.city-fan.org/ftp/contrib/yum-repo/city-fan.org-release-1-13.rhel6.noarch.rpm
sudo yum install -y libcurl

step8. FuelPHPをインストールする

$ oil create <project_name>
  • gitプロトコルが使えない場合
    GitHubからcloneするとcomposer実行時にtokenが必要になる場合があるため、今回はzipをdownloadする
### FuelPHP install ###
# oil install
curl get.fuelphp.com/oil | sh

# create target directory
sudo mkdir -p /srv/example

# fuelphp1.7.3 download
cd /usr/local/src
sudo wget -O fuelphp-1.7.3.zip http://fuelphp.com/files/download/34
sudo unzip fuelphp-1.7.3.zip -d /srv/example
cd /srv/example
sudo mv fuelphp-1.7.3 fuelphp
cd fuelphp
sudo php oil refine install

step9. httpd(apache)を再起動する

# httpd restart
sudo service httpd restart

5. 動作確認

step1. 仮想マシンを作成する

$ vagrant up

step2. 動作確認

ブラウザで「192.168.100.11」を開いて下記画面が表示されればOK
f:id:ita3y:20151123194535p:plain

Swiftでplistを利用して環境(開発、本番等)ごとに設定値を変える

1. Custom Configurationを追加する

step1. PROJECT -> info -> Configurationsから追加

「+」->「Duplicate "Debug" Configuration」
追加前 f:id:ita3y:20151123161536p:plain
追加後 f:id:ita3y:20151123160034p:plain

2. Info.plistを編集する

step1. Configurationを追加する

Key: Configuration, Value: ${CONFIGURATION} を追加
f:id:ita3y:20151123160609p:plain

step2. 出力を確認

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Configuration取得
    let configuration = NSBundle.mainBundle().infoDictionary!["Configuration"]
    print("Current Configuration > \(configuration)")

    return true
}

こんな感じに出力されればOK

Current Configuration > Optional(Debug)

3. Schemesを変更する

step1. Edit SchemesからBuild Configurationを変更する

f:id:ita3y:20151123163641p:plain

step2. CocoaPodsを更新する(CocoaPods未使用の場合は不要)

追加したConfiguration(ここではDevelopment)のxcconfigが無いとエラーになるので更新する

$ pod update

4. Configuration.plistを追加する

step1. plistを新規作成

f:id:ita3y:20151123161922p:plain

step2. 項目を追加

f:id:ita3y:20151123162513p:plain

step3. 出力を確認

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let mainBundle = NSBundle.mainBundle()
    // Configuration取得
    let configuration = mainBundle.infoDictionary!["Configuration"]
    
    // Configurations.plist読み込み
    let path = mainBundle.pathForResource("Configurations", ofType: "plist")
    let configurations = NSDictionary(contentsOfFile: path!)

    // Load Variables for Current Configuration
    let variables = configurations?.objectForKey(configuration!) as! [String : AnyObject]

    print(variables["APIEndpoint"])

    return true
}

こんな感じに出力されればOK

Optional(http://development.example.com)

5. 使いやすくする

step1. Configurationクラスを新規作成

(省略)

step2. Configurationクラスを編集

import Foundation

final class Configuration {

    private static let sharedInstance = Configuration()
    private var configuration: String
    private var variables: [String: AnyObject]

    private init() {

        // Singletonの確認用
        print("Configuration initialization")

        let mainBundle = NSBundle.mainBundle()
        // Fetch Current Configuration
        self.configuration = (mainBundle.infoDictionary?["Configuration"]) as! String

        // Load Configurations
        guard let path = mainBundle.pathForResource("Configurations", ofType: "plist") else {
            self.variables = [:]
            return
        }
        let configurations =  NSDictionary(contentsOfFile: path)
        // Load Variables for Current Configuration
        self.variables = configurations?.objectForKey(self.configuration) as! [String : AnyObject]
    }

    class func Configuration() -> String {
        return sharedInstance.configuration
    }

    class func APIEndpoint() -> String {
        guard let endpoint = sharedInstance.variables["APIEndpoint"] else {
            return ""
        }
        return endpoint as! String
    }

    class func isLoggingEnabled() -> Bool {
        guard let enabled = sharedInstance.variables["LoggingEnabled"] else {
            return false
        }
        return enabled as! Bool
    }
}

step3. 動作確認

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    for i in 1...5 {
        print("\(i)回目: \(Configuration.APIEndpoint())")
    }

    return true
}

こんな感じに出力されればOK

Configuration initialization
1回目: http://development.example.com
2回目: http://development.example.com
3回目: http://development.example.com
4回目: http://development.example.com
5回目: http://development.example.com

6. 参考サイト

iOS Quick Tip: Managing Configurations With Ease - Envato Tuts+ Code Tutorial

The Right Way To Write a Singleton — KrakenDev

UITableViewでセクション毎に開閉(アコーディオン)を作ってみたかった。

今更ながらやってみました。

手順という程でも無いけど、
あえて分けるならこんな感じ。

  • セクションに設定するカスタムビュー作成
- (id)initWithTitle:(NSString *)title
       sectionIndex:(NSInteger)index
             isOpen:(BOOL)isOpen
{
    self = [super init];
    if (self) {
        [self setDefaultStyle];
        [self setTitle:title];
        [self setIndex:index];
        [self setOpenState:isOpen];
        [self switchArrowImg];
        [self addTapGesture];
    }
    return self;
}
  • カスタムビューにタップジェスチャーを追加
- (void)addTapGesture
{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(sigleTapped)];
    [self addGestureRecognizer:singleTap];
}
  • セクションにカスタムビューを設定
/**
 セクションヘッダーのコンテンツを設定する
 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.isHideSection) {
        return nil;
    }
    NSString *title = [sectionList_ objectAtIndex:section];
    BOOL isOpen = [self isEmptyList:sectionStateList_] ? YES : [[sectionStateList_ objectAtIndex:section] boolValue];
    CustomSectionHeaderView *containerView = [[CustomSectionHeaderView alloc] initWithTitle:title
                                                                               sectionIndex:section
                                                                                     isOpen:isOpen];
    containerView.delegate = self;
    
    return containerView;
}
  • カスタムビューのデリゲートを実装
/**
 シングルタップ時に実行される処理
 
 @param sectionIndex セクションのインデックス
 @param isOpen セクションの開閉状態
 */
- (void)didSectionHeaderSingleTap:(NSInteger)sectionIndex isOpen:(BOOL)isOpen
{
    [sectionStateList_ replaceObjectAtIndex:sectionIndex
                                 withObject:[NSNumber numberWithBool:isOpen]];
    [self.tableView beginUpdates];

    if (isOpen) {
        [self openSectionContents:sectionIndex];
    } else {
        [self closeSectionContents:sectionIndex];
    }
    
    [self.tableView endUpdates];
}

ソースはGitHubにあります。
https://github.com/negibouze/UITableViewAccordionSection

Markdown記法勉強しないと・・・。