LoginSignup
93
86

More than 5 years have passed since last update.

swiftでiosアプリケーションをバックグラウンドで実行してみた

Last updated at Posted at 2015-02-11

どうも、iron千葉です。
ぐぐっても、あまり記事なかったので残しておきます。

環境

  • Xcode6.1.1
  • swift

やりたいこ

iosアプリケーションで、バックグラウンドで処理をしたい。swiftで。
UIApplicationDelegateを利用して、バックグランドで非定期的に処理を実行する。

バックグラウンドの有効化

バックグラウンド実行の有効化をします。
全画面_2015_02_11_18_37.jpg

コード

Appdelegate.swiftに処理を追加します。

Appdelegate.swift


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
        return true
    }



アプリ起動時に実行される didFinishLaunchingWithOptions の中に、バックグランドで実行されるインターバルを指定する。これを指定しないと、バックグラウンド実行は有効にならない。

そして、 performFetchWithCompletionHandler にバックグラウンドで実際に実行させる処理の内容を書く。
例として、printlnで現在時間をコンソールに出力する処理を書いてます。

Appdelegate.swift
    func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        let now = NSDate()

        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"

        let string = formatter.stringFromDate(now)

        println(string)
        completionHandler(UIBackgroundFetchResult.NewData)
    }

また、処理が完了したらcompletionHandlerにて、処理の終了ステータスを返す必要があります。

  • フェッチ処理にてデータが取得できた場合:UIBackgroundFetchResult.NewData
  • フェッチ処理にて更新データがなかった場合:UIBackgroundFetchResult.NoData
  • フェッチ処理が失敗した場合:UIBackgroundFetchResult.Faild

テスト

シュミレータを起動して、動作テストをします。
メニューのDebug > Simulate Background Fetch

日付と時間が出力されます。

全画面_2015_02_10_23_05.jpg

全画面_2015_02_11_9_23.jpg

まとめ

と、簡単ですが以上です。
実機で試してないですが、動くはずです。

93
86
1

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
93
86