ios - Swift:使用未解析的标识符。目标成员(member)

标签 ios swift

下面有一个与 sleep 分析相关的 Swift 脚本。

错误:

View Controller has no member 'updateTime'.

我尝试使用文件检查器添加此目标并将其添加到目标成员身份,但目标本身不会显示,这太奇怪了。任何反馈将不胜感激。

PS:另一条错误消息不断弹出,并未说明“错误”是 if != nil 语句的未解析标识符。如有任何帮助,我们也将不胜感激。

import UIKit
import HealthKit

    let healthStore = HKHealthStore()
class ViewController: UIViewController {
    @IBOutlet var displayTimeLabel: UILabel!

    var startTime = TimeInterval()
    var timer:Timer = Timer()
    var endTime: NSDate!
    var alarmTime: NSDate!

    func saveSleepAnalysis() {

        //1. startTime(alarmTime) and endTime are NSDate Objects//
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
            //we create a new object that we want to add into our Health app(This is our INBED object)//
            let object1 = HKCategorySample(type:sleepType, value: HKCategoryValueSleepAnalysis.inBed.rawValue, start: self.alarmTime as Date, end: self.endTime as Date)
            // Time to save the object//
            healthStore.save(object1, withCompletion: { (success, errpr) -> Void in

            if error != nil
                {
                    return
                }

                if success {
                    print("My new data was saved in HealthKit")

                } else {
                    //something happened again//
                }
            })
            //This our ASLEEP object//
            let object2 = HKCategorySample(type:sleepType, value: HKCategoryValueSleepAnalysis.asleep.rawValue, start: self.alarmTime as Date, end: self.endTime as Date)
            //now we save our objects to our mainLibrary known as HealthStore
            healthStore.save(object2, withCompletion: { (success, error) -> Void in
                if error != nil {
                        //Something went wrong//
                    return

                    if success {
                        print("My new data (2: Asleep data) was saved into HealthKit")
                    } else {
                           //something happened again//
                    }
                }
        }
    )}

        func retrieveSleepAnalysis() {
            //first, define our object type that we watn again in BOOLEAN FORMAT//
            if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {

                //use sortDescriptor to get teh recent data first: so from MostRecentData to PastData//
                let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)

                //we create our query with a block completion to execute
                let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit:30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in

                    if error != nil {
                        //something happends//
                        return
                    }
                    if let result = tmpResult {

                        //then i want the computer to do something with my data//
                        for item in result {
                            if let sample = item as? HKCategorySample {
                                let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "InBed" : "Asleep"
                                print("Healthkit sleep: \(sample.startDate) \(sample.endDate) = value: \(value)")
                            }
                        }
                    }
                }

                //finally, we execute our query: Print out our output file //
                healthStore.execute(query)
            }
        }
        func viewDidLoad() {
        super.viewDidLoad()

        let typestoRead = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!
            ])

        let typestoShare = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!
            ])
            healthStore.requestAuthorization(toShare: typestoShare, read: typestoRead) { (success, error) -> Void in
            if success == false {
                    NSLog(" Display not allowed")
            }
        }
    }


func updateTime() {
        let currentTime = NSDate.timeIntervalSinceReferenceDate

        //Find the difference between current time and start time.
        var elapsedTime: TimeInterval = currentTime - startTime

        //calculate the minutes in elapsed time.
        let minutes = UInt8(elapsedTime / 60.0)
        elapsedTime -= (TimeInterval(minutes) * 60)

        //calculate the seconds in elapsed time.
        let seconds = UInt8(elapsedTime)
        elapsedTime -= TimeInterval(seconds)

        //find out the fraction of milliseconds to be displayed.
        let fraction = UInt8(elapsedTime * 100)

        //add the leading zero for minutes, seconds and millseconds and store them as string constants

        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)
        let strFraction = String(format: "%02d", fraction)

        //concatenate minuets, seconds and milliseconds as assign it to the UILabel
        displayTimeLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
    }


        func start(sender: AnyObject) {
            alarmTime = NSDate()
            if (!timer.isValid) {
                let Selector : Selector = #selector(ViewController.updateTime)
                timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: Selector, userInfo: nil, repeats: true)
                startTime = NSDate.timeIntervalSinceReferenceDate
            }

        }



        func stop(sender: AnyObject) {
            endTime = NSDate()
            saveSleepAnalysis()
            retrieveSleepAnalysis()
            timer.invalidate()
        }

        func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

        }
    }

最佳答案

用此替换您的代码

import UIKit
import HealthKit

let healthStore = HKHealthStore()
class ViewController: UIViewController {
    @IBOutlet var displayTimeLabel: UILabel!

    var startTime = TimeInterval()
    var timer:Timer = Timer()
    var endTime: NSDate!
    var alarmTime: NSDate!

    func saveSleepAnalysis() {

        //1. startTime(alarmTime) and endTime are NSDate Objects//
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
            //we create a new object that we want to add into our Health app(This is our INBED object)//
            let object1 = HKCategorySample(type:sleepType, value: HKCategoryValueSleepAnalysis.inBed.rawValue, start: self.alarmTime as Date, end: self.endTime as Date)
            // Time to save the object//
            healthStore.save(object1, withCompletion: { (success, errpr) -> Void in

                if errpr != nil
                {
                    return
                }

                if success {
                    print("My new data was saved in HealthKit")

                } else {
                    //something happened again//
                }
            })
            //This our ASLEEP object//
            let object2 = HKCategorySample(type:sleepType, value: HKCategoryValueSleepAnalysis.asleep.rawValue, start: self.alarmTime as Date, end: self.endTime as Date)
            //now we save our objects to our mainLibrary known as HealthStore
            healthStore.save(object2, withCompletion: { (success, error) -> Void in
                if error != nil {
                    //Something went wrong//
                    return

                    if success {
                        print("My new data (2: Asleep data) was saved into HealthKit")
                    } else {
                        //something happened again//
                    }
                }
            }
            )}


    }

    func retrieveSleepAnalysis() {
        //first, define our object type that we watn again in BOOLEAN FORMAT//
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {

            //use sortDescriptor to get teh recent data first: so from MostRecentData to PastData//
            let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)

            //we create our query with a block completion to execute
            let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit:30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in

                if error != nil {
                    //something happends//
                    return
                }
                if let result = tmpResult {

                    //then i want the computer to do something with my data//
                    for item in result {
                        if let sample = item as? HKCategorySample {
                            let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "InBed" : "Asleep"
                            print("Healthkit sleep: \(sample.startDate) \(sample.endDate) = value: \(value)")
                        }
                    }
                }
            }

            //finally, we execute our query: Print out our output file //
            healthStore.execute(query)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let typestoRead = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!
            ])

        let typestoShare = Set([
            HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!
            ])
        healthStore.requestAuthorization(toShare: typestoShare, read: typestoRead) { (success, error) -> Void in
            if success == false {
                NSLog(" Display not allowed")
            }
        }
    }


    func updateTime() {
        let currentTime = NSDate.timeIntervalSinceReferenceDate

        //Find the difference between current time and start time.
        var elapsedTime: TimeInterval = currentTime - startTime

        //calculate the minutes in elapsed time.
        let minutes = UInt8(elapsedTime / 60.0)
        elapsedTime -= (TimeInterval(minutes) * 60)

        //calculate the seconds in elapsed time.
        let seconds = UInt8(elapsedTime)
        elapsedTime -= TimeInterval(seconds)

        //find out the fraction of milliseconds to be displayed.
        let fraction = UInt8(elapsedTime * 100)

        //add the leading zero for minutes, seconds and millseconds and store them as string constants

        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)
        let strFraction = String(format: "%02d", fraction)

        //concatenate minuets, seconds and milliseconds as assign it to the UILabel
        displayTimeLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
    }


    func start(sender: AnyObject) {
        alarmTime = NSDate()
        if (!timer.isValid) {
            let Selector : Selector = #selector(ViewController.updateTime)
            timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: Selector, userInfo: nil, repeats: true)
            startTime = NSDate.timeIntervalSinceReferenceDate
        }

    }



    func stop(sender: AnyObject) {
        endTime = NSDate()
        saveSleepAnalysis()
        retrieveSleepAnalysis()
        timer.invalidate()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

关于ios - Swift:使用未解析的标识符。目标成员(member),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626580/

相关文章:

iOS:我可以检测设备屏幕是否打开/关闭吗?

ios - MKMapView 与 iOS 8 崩溃

ios - UITapGestureRecognizer 不适用于 UITextField 的自定义子类

ios - 使用 Swift 5 截取屏幕截图返回黑色图像而不是应用程序的屏幕

c++ - 使用在 ios 上运行的 qt 应用程序构建 boost

ios - 在 ObjC 中使用 Swift 库

swift - UIView 的动画方法没有出现

arrays - 减少要在 Swift 中设置的数组

Swift: 'use of unresolved identifier' - 如何更改变量并在不同函数中使用该变量?

ios - 在 Swift 中转换 UTC 时间