保存位置并快速上传位置

时间:2015-11-13 11:26:30

标签: ios swift core-location

我的应用程序遇到了这个问题,我猜我正在接近这个问题。 我希望每十秒钟将当前位置保存到手机中。 我希望每隔一分钟将当前位置上传到网络服务器。

我该怎么做? 到目前为止,这是我的代码。

 self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters

    }


}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
    let newLocation = locations.last! as CLLocation
    saveLocations.saveLocation(newLocation.coordinate.longitude, latitude: newLocation.coordinate.latitude)

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func startButtonClicked(sender: AnyObject) {
    if(startButton.titleLabel?.text == "STARTA") {
        tenSecTimer = NSTimer.scheduledTimerWithTimeInterval(10, target:self, selector: Selector("tenSecTimer:"), userInfo: nil, repeats: true)
        sixtySecTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("sixtySecondsTimer:"), userInfo: nil, repeats: true)
        locationManager.startUpdatingLocation()
        startButton.setTitle("STOPPA", forState: UIControlState.Normal)
        startButton.backgroundColor = UIColor.redColor()
    } else {
        tenSecTimer.invalidate()
        sixtySecTimer.invalidate()
        locationManager.stopUpdatingLocation()
        startButton.setTitle("STARTA", forState: UIControlState.Normal)
        startButton.backgroundColor = UIColor.greenColor()
    }
}

//One minute upload 
func sixtySecondsTimer(timer : NSTimer){
    print("60SEK")
}

//10Second timer
func tenSecTimer(timer : NSTimer) {
    print("10SEK")
}

1 个答案:

答案 0 :(得分:3)

要获取自动提醒,要求用户获得使用其位置的权限,您需要将NSLocationAlwaysUsageDescription和/或NSLocationWhenInUseUsageDescription密钥添加到Info.plist,当然取决于您将使用的位置更新类型。它可能如下所示:

<key>NSLocationWhenInUseUsageDescription</key>
<string>We need to know your location because it makes it easier to stalk you</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need to know your location because it makes it easier to stalk you</string>

===

更新1

OP提供了有关该问题的更多详细信息

===

要发出POST请求,您可以使用NSURLSession或一些流行的第三方网络库。许多人使用AFNetworking(Obj-C)或Alamofire(Swift)来使他们的生活更轻松,代码更漂亮。您可以通过CocoaPods安装这两个。

以下示例将基于Alamofire,但AFNetworking的代码非常相似。 NSURLSession是一个不同的案例,有时需要复杂的多线程应用程序或者您希望提供更好的后台支持。

注意:此代码只是一个演示,并且都包含在同一个UIViewController中,这是不好的做法。您需要将其自身重构为单独的模型以获得更好的代码。此外,NSDateFormatter扩展程序中的NSDate效率极低。此外,此测试使用HTTP,因此ATS已关闭。

//
//  ViewController.swift
//  LocationUpload
//
//  Created by Stefan Veis Pennerup on 13/11/15.
//  Copyright © 2015 Kumuluzz. All rights reserved.
//

import UIKit
import CoreLocation
import Alamofire

class ViewController: UIViewController, CLLocationManagerDelegate {

    // MARK: - Properties

    private let locationManager = CLLocationManager()
    private var tenSecTimer = NSTimer()
    private var sixtySecTimer = NSTimer()
    private var savedLocations = [CLLocation]()

    // MARK: - Storyboard outlets

    @IBOutlet weak var startButton: UIButton!

    // MARK: - Lifecycle methods

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        requestLocationAuthorization()
    }

    // MARK: - Storyboard actions

    @IBAction func startButtonClicked(sender: UIButton) {
        let buttonText = startButton.titleLabel?.text!
        let shouldTurnUpdatesOn = buttonText == "STARTA"
        toggleLocationUpdates(shouldTurnUpdatesOn)
    }

    // MARK: - Authorization

    private func requestLocationAuthorization() {
        self.locationManager.requestAlwaysAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        }
    }

    // MARK: - Helper methods

    private func toggleLocationUpdates(toggle: Bool) {
        if toggle {
            tenSecTimer = NSTimer.scheduledTimerWithTimeInterval(10,
                target:self,
                selector: Selector("tenSecTimer:"),
                userInfo: nil, repeats: true)
            sixtySecTimer = NSTimer.scheduledTimerWithTimeInterval(60,
                target: self,
                selector: Selector("sixtySecondsTimer:"),
                userInfo: nil, repeats: true)
            locationManager.startUpdatingLocation()
            startButton.setTitle("STOPPA", forState: UIControlState.Normal)
            startButton.backgroundColor = UIColor.redColor()
        }
        else {
            tenSecTimer.invalidate()
            sixtySecTimer.invalidate()
            locationManager.stopUpdatingLocation()
            startButton.setTitle("STARTA", forState: UIControlState.Normal)
            startButton.backgroundColor = UIColor.greenColor()
        }
    }

    // MARK: - CLLocationManagerDelegate

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("\(self.dynamicType), locationManager:didUpdateLocations")
        savedLocations += locations
    }

    // MARK: - Callback methods

    func sixtySecondsTimer(timer : NSTimer) {
        print("\(self.dynamicType), sixtySecondsTimer")
        uploadLocationsToBackend(savedLocations)
    }

    func tenSecTimer(timer : NSTimer) {
        print("\(self.dynamicType), tenSecTimer")
    }

    // MARK: - Parsers

    private struct JsonConstants {
        static let Locations = "locations"
        static let Timestamp = "timestamp"
        static let Latitude = "latitude"
        static let Longitude = "longitude"
    }

    private func parseLocationsToDictionary(locations: [CLLocation]) -> [String: AnyObject] {

        var locationsDictionaries = [[String: AnyObject]]()

        for loc in locations {
            let locDict: [String: AnyObject] = [
                JsonConstants.Timestamp: loc.timestamp.toISO8601(),
                JsonConstants.Latitude: loc.coordinate.latitude,
                JsonConstants.Longitude: loc.coordinate.longitude
            ]
            locationsDictionaries += [locDict]
        }

        return [JsonConstants.Locations: locationsDictionaries]
    }

    // MARK: - Network

    private func uploadLocationsToBackend(locations: [CLLocation]) {
        let url = "http://httpbin.org/post"
        let params = parseLocationsToDictionary(locations)
        Alamofire.request(.POST, url, parameters: params, encoding: .JSON, headers: nil)
            .responseJSON { response in
            print("\(self.dynamicType) response: \(response)")
        }
    }
}

extension NSDate {

    func toISO8601() -> String {
        let iso8106Formatter = NSDateFormatter()
        iso8106Formatter.timeZone = NSTimeZone(name: "UTC")
        iso8106Formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        iso8106Formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        return iso8106Formatter.stringFromDate(self)
    } 
}