Update CLLocation Manager on another method

瘦欲@ 提交于 2019-12-25 09:25:32

问题


I need to update my location outside the func locationManager

I have 2 labels that are being updated every second, and a call to an API from a HTTP POST Request. The problem is when I call the API (when I press the startButton, only the first value is passed :-/

 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:


I did it myself, I had a new timer and call sendPosition every x seconds

It's working



来源:https://stackoverflow.com/questions/39757134/update-cllocation-manager-on-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!