2017-08-11 91 views
0

我有一个关于睡眠分析的Swift脚本。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. 
    } 

     } 
    } 
+0

更换你的代码看起来像你可能有一些缩进和可能涉及的范围的问题。你确定函数updateTime是在类中定义的吗? – ryantxr

回答

0

与此

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. 
    } 

} 
+0

此代码的问题在第50行中:“返回后的代码将永远不会执行” – Flavia

+0

我的代码的第50行?你的问题是无法引用UpdateTime和我的代码我解决了这个问题,如果有另一个问题,请让我知道,因为我没有建立的代码,我刚刚解决UpdateTime问题 –

+0

问题已解决。原来这是软件本身的问题,谢谢你的帮助。 – Flavia