1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

(初心者向け)Swift3.0で初アプリ - 万歩計アプリ

Last updated at Posted at 2017-10-03

Swift3.0を使って簡単なiPhoneアプリを作ってみます
万歩計アプリです。ViewController.swiftに下記をコピペします
Info.plistでPrivary - Motion Usage Descriptionを登録します


import UIKit
import CoreMotion

class ViewController: UIViewController {
    
    var myPedometer: CMPedometer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         // 画面の背景色を指定
        self.view.backgroundColor = UIColor(red:1.0,green:1.0,blue:0.875,alpha:1.0)

        // 歩数表示ラベルを作成
        let myStepLabel: UILabel = UILabel(frame: CGRect(x:0,y:0,width:150,height:150))
        // ラベルの背景色
        myStepLabel.backgroundColor = UIColor(red:1.0,green:0.875,blue:1.0,alpha:1.0)
        // ラベルの背景色
        myStepLabel.layer.masksToBounds = true
        myStepLabel.layer.cornerRadius = 75.0
        myStepLabel.textColor = UIColor.black
        myStepLabel.shadowColor = UIColor.gray
        myStepLabel.font = UIFont.systemFont(ofSize: CGFloat(30))
        myStepLabel.textAlignment = NSTextAlignment.center
        myStepLabel.layer.position = CGPoint(x: self.view.bounds.width/2,y: 200)
        // Viewに追加
        self.view.addSubview(myStepLabel)

        // 歩数計を生成
        myPedometer = CMPedometer()
        
        // ペドメーター(歩数計)で計測開始
        myPedometer.startUpdates(from: NSDate() as Date, withHandler: { (pedometerData, error) in
            if let e = error {
                print(e.localizedDescription)
                return
            }
            guard let data = pedometerData else {
                return
            }
            let myStep = data.numberOfSteps
            myStepLabel.text = "\(myStep) 歩"
        })
    }
    
}

  • iPhoneの万歩計データは非同期に更新されるので慌てずに稼働を確認します。「ヘルスケア」メニューからも歩数のデータを確認可能です
  • 万歩計の歩数の取得を参考にさせていただきました。
1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?