在另一个方法上更新CLLocation Manager

时间:2016-09-28 20:32:38

标签: cllocationmanager

我需要在func locationManager之外更新我的位置

我有2个标签每秒更新一次,并从HTTP POST请求调用API。问题是当我调用API时(当我按下startButton时,只传递第一个值: - /

 class PressStartViewController: UIViewController,CLLocationManagerDelegate {

    var manager: CLLocationManager!
    var userLocation: CLLocation! = nil

    var timer = NSTimer()
    var time = 0
    var minute = 0

    @IBOutlet var bearingLabel: UILabel!
    @IBOutlet var speedlabel: UILabel!

    @IBOutlet var timerLabel: UILabel!
    @IBOutlet var minuteLabel: UILabel!

    @IBOutlet var startButton: UIButton!

    @IBOutlet var startImage: UIImageView!
    @IBOutlet var finishImage: UIImageView!

    @IBOutlet var resumeImage: UIImageView!
    func increaseTimer() {

        time++
        if time > 9 {
            timerLabel.text = "\(time)"
        } else {
            timerLabel.text = "0\(time)"
        }
        if time > 59 {
            time = 0
            timerLabel.text = "00"
            minute++
            if minute > 9 {
                minuteLabel.text = "\(minute)"
            } else {
                minuteLabel.text = "0\(minute)"
            }
        }

    }



    @IBAction func start(sender: AnyObject) {
         timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true)
        startImage.hidden = true
        resumeImage.hidden = false
        finishImage.hidden = false
        sendPosition()

    }



    @IBAction func resume(sender: AnyObject) {
        timer.invalidate()
        startImage.hidden = false
        resumeImage.hidden = true
        finishImage.hidden = true
    }

    @IBAction func finish(sender: AnyObject) {
        timer.invalidate()
        time = 0
        minute = 0
        timerLabel.text = "00"
        minuteLabel.text = "00"
    }


    override func viewDidLoad() {
        super.viewDidLoad()
      //  print ("ent viewdidload")
        // Do any additional setup after loading the view.
        //print (userId!)
        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingHeading()
        manager.startUpdatingLocation()
        resumeImage.hidden = true
        finishImage.hidden = true


    }

    func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {

        let heading = newHeading.magneticHeading
        self.bearingLabel.text = String(format: "%.0fº",heading)
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        userLocation = locations[0]
        let bearing = userLocation.course
        let knots = userLocation.speed
        //self.bearingLabel.text = String(format: "%.0fº",bearing)
        self.speedlabel.text = String(format: "%.1f knots",knots * 1.94384)
       // print(locations)

    }

    func sendPosition() {
        manager.startUpdatingLocation()
        manager.startUpdatingHeading()
        let Speed = userLocation.speed
        let Bearing = userLocation.course
        let Latitude = userLocation.coordinate.latitude
        let Longitude = userLocation.coordinate.longitude
        let clientTimestamp = NSDate().iso8601
        let BoxId = UIDevice.currentDevice().identifierForVendor!.UUIDString
        let SessionId = NSUUID().UUIDString
        let Bearer = userId!
        let spinningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        spinningActivity.labelText = "Loading"
        spinningActivity.detailsLabelText = "Please wait"
        let myUrl = NSURL(string: "https://www.example.com/api/v1/positions/");

        let request = NSMutableURLRequest(URL:myUrl!,cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0);
        request.HTTPMethod = "POST";



        let postString = "Speed=\(Speed)&Bearing=\(Bearing)&Latitude=\(Latitude)&Longitude=\(Longitude)&clientTimestamp=\(clientTimestamp)&BoxId=\(BoxId)&SessionId=\(SessionId)"
        //print (postString)
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

        request.setValue("Bearer \(Bearer)", forHTTPHeaderField: "Authorization")
        /////////////////
        print (Bearer)
        //print (request)

        NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            print (response!)
            dispatch_async(dispatch_get_main_queue())
            {

                spinningActivity.hide(true)


                if(error != nil)
                {
                    //Display an alert message
                    let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert);
                    let okAction = UIAlertAction(title: "OK1", style: UIAlertActionStyle.Default, handler:nil)
                    myAlert.addAction(okAction);
                    self.presentViewController(myAlert, animated: true, completion: nil)
                    return
                }



                do {
                    print ("linha 1")
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
                    if let parseJSON = json {
                        print ("linha 3")
                        //                        let userId = parseJSON["access_token"] as? String
                        //                        if(userId != nil)
                        //                        {
                        //                            print ("linha 4")
                        //                            //  NSUserDefaults.standardUserDefaults().setObject(parseJSON["userFirstName"], forKey: "userFirstName")
                        //                            //    NSUserDefaults.standardUserDefaults().setObject(parseJSON["userLastName"], forKey: "userLastName")
                        //                            NSUserDefaults.standardUserDefaults().setObject(parseJSON["access_token"], forKey: "userId")
                        //                            NSUserDefaults.standardUserDefaults().synchronize()
                        //
                        //                            // take user to a protected page
                        //                            /*
                        //                             let mainPage = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController
                        //
                        //                             let mainPageNav = UINavigationController(rootViewController: mainPage)
                        //                             let appDelegate = UIApplication.sharedApplication().delegate
                        //
                        //                             appDelegate?.window??.rootViewController = mainPageNav
                        //                             */
                        //
                        //                            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        //
                        //                            appDelegate.buildNavigationDrawer()
                        //
                        //
                        //                        } else {
                        //                            print ("linha 5")
                        //                            // display an alert message
                        //                            let userMessage = parseJSON["message"] as? String
                        //                            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
                        //                            let okAction = UIAlertAction(title: "OK2", style: UIAlertActionStyle.Default, handler:nil)
                        //                            myAlert.addAction(okAction);
                        //                            self.presentViewController(myAlert, animated: true, completion: nil)
                        //                        }
                        //                        print ("linha 6")
                    }
                } catch
                {
                    print(error)
                }

            }


        }).resume()

    }

1 个答案:

答案 0 :(得分:0)

我自己做了,我有一个新的计时器,每x秒调用一次sendPosition

它的工作