ラベル iOS の投稿を表示しています。 すべての投稿を表示
ラベル iOS の投稿を表示しています。 すべての投稿を表示

2016年5月22日日曜日

iOSでFirebase Analyticsを使う


(引用元:https://firebase.google.com)

セットアップ

公式Page
https://firebase.google.com/docs/ios/setup

CocoaPodを利用してインストールします。
podの初期設定を実行。
pod init
Podfile を開いて以下を追加します。
pod 'Firebase/Core'
podのインストールを実行します。
pod install

Analytics以外の機能を使用するには、次の公式サイトに記載されているpodを追加しましょう。
https://firebase.google.com/docs/ios/setup#available_pods


import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // init Firebase
        FIRApp.configure()
        return true
    }
}


イベント送信方法

以下、宣言済みのイベントがあり、ヘッダーファイルに定義されているので参照。
イベント:FIReventNames.h
パラメータ:FIRParameterNames.h


FIRAnalytics.logEventWithName(kFIREventSelectContent, parameters: [
  kFIRParameterContentType:"cont",
  kFIRParameterItemID:"1"
  ])


ユーザープロパティ

アプリのユーザーをカテゴライズすることが可能です。
FIRAnalytics.setUserPropertyString(food, forName: "favorite_food")

2015年10月22日木曜日

[Swift][GCM]iOSでGoogle Cloud Messageを使う

iOSでGoogle Cloud Message 3.0を使ったので、はまりどころのメモです。
基本的なことは本家サイトを参照ください。
https://developers.google.com/cloud-messaging/ios/client?ver=swift

APNs用にデータを追加する

データ構造はGCM 2.0に以下のAPNsでも使用できるパラメータを追加すればデバイスに届きます。
  "content_available" : "true"
  "notification" : {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark"
    }

もし、デバイスに届かない場合はcontent_availableの値を確認しましょう。"true"というStringではなく、true / falseのBoolが正しいです。

Push受信しても鳴動しない

notificationにsoundパラメータを追加しましょう。
https://developers.google.com/cloud-messaging/http-server-ref
https://developer.apple.com/jp/documentation/RemoteNotificationsPG.pdf

アプリ起動していない状態でバックグラウンド受信しない

priorityの追加
priorityパラメータを追加して、10を指定しましょう。
https://developers.google.com/cloud-messaging/http-server-ref
https://developer.apple.com/jp/documentation/RemoteNotificationsPG.pdf
iOSアプリ側の設定
Background fetch modeをONにしましょう。
AppDelegateにて、MinimumBackgroundFetchIntervalをセットします。DefaultはNeverになっているため、Background fetchしません。
  application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)

2015年8月21日金曜日

iOS8.xでUITableViewAutomaticDimensionを使うと、セル位置が正常にならない

iOS8.xでTableViewのセル高さの自動調整が可能です。

    self.tableView.rowHeight = UITableViewAutomaticDimension



ただし、TableViewからセル選択により画面遷移後、戻ってきたときなど再表示をするとセル位置が調整されていないことがあります。 対策として、一度表示したセルの高さを保持しておいて、estimatedHeightForRowAtIndexPathで値を返します。

    var cellHeight:Dictionary = ["":0]
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        cell.contentView.updateConstraints()
        self.cellHeight[String(indexPath.item )] = Float(cell.frame.size.height)
        
    }
    
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if(self.cellHeight[String(indexPath.item )] != nil){
            return CGFloat(self.cellHeight[String(indexPath.item )]!)
        }
        return self.tableView.estimatedRowHeight
        
    }

2015年2月26日木曜日

Swiftでパラメータ付きPOSTリクエストを行う

SwiftでWebAPIのリクエストを行う際、POSTメソッドを使う必要がありました。
次は非同期でリクエストを行う、NSURLConnectionクラスのsendAsynchronousRequestメソッドを用いたサンプルソースです。

        // URLセット
        let url = NSURL(string: "https://test.url.jp")
        var request : NSMutableURLRequest = NSMutableURLRequest(URL: url!)

        // POSTメソッド指定
        request.HTTPMethod = "POST"
        
        // POSTパラメータ
        var bodyData: String = "key1=value1&key2=value2"
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
        // ヘッダの指定
        request.setValue("HeaderValue", forHTTPHeaderField: "HeaderName")
        
        //asyncで実行
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: responseHandler)

2015年2月24日火曜日

SwiftなCocoa Touch FrameworkでCommonCryptoを使う

Swiftを使ってCocoa Touch Frameworkを作成しています。
どうしても、CommonCryptoを使う必要があり手段を探していました。

以下、参考になったサイトです。
Importing CommonCrypto in a Swift framework
CommonHMAC in Swift

手順は次のようになります。

  1. CommonCryptoというディレクトリを作成
  2. module.mapというファイルを作成
  3. プロジェクト設定のBuild Settings -> Swift Compiler - Search Paths -> Import Pathsに、上記のCommonCryptoディレクトリを指定



次はサンプルです。 module.mapにSDK内のヘッダファイルのPathを記述します。

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

このあたり、公式Developerサイトに書いてるのかな?

2015年2月21日土曜日

Unit testで非同期処理のWaitをする

XcodeでiOS開発の勉強をはじめました。
いきなりですが、UnitTestネタです。テストしないもの、エンジニアにあらずです。

参考:Writing Test Classes and Methods

waitForExpectationsWithTimeoutで非同期処理の待ち状態を指定

標準テストフレームワークのXCTestExpectationとXCTestCase.waitForExpectationsWithTimeoutを組み合わせて実装します。
手順は次のようになります。

  1. XCTestCase.expectationWithDescriptionをコールして、XCTestExpectationを取得 
  2. XCTestCase.waitForExpectationsWithTimeoutで、waitを指定 
  3. 非同期処理終了のタイミングで、XCTestExpectation.fulfill()。もし、waitForExpectationsWithTimeoutで指定した時間内にコールしなければfailとなる

サンプルプログラムです。
    func testPerformAsyncRequest(){
        // XCTestExpectationの取得
        let expectation = self.expectationWithDescription("client key")

        // 非同期処理のコールバック処理完了後、expectation.fulfill()をコール
        expectation.fulfill()
        
        //waitの時間指定
        self.waitForExpectationsWithTimeout(5, handler: nil)
        
    }