问题描述:

I have this problem with my application, guess i'm approaching this problem wrong.

For every ten seconds i wish to save my current location to the phone.

And every one minute i wish to upload the current location to a web server.

How do i do this?

This is my code so far.

 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")

}

网友答案:

In order to get the automatic alert asking the user for permission to use their location, then you will need to add the NSLocationAlwaysUsageDescription and/or NSLocationWhenInUseUsageDescription keys to your Info.plist, of course depending on which location update type you will make use of. It could look like the following:

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

===

UPDATE 1

OP provided more details about the problem

===

To make a POST request then you can either make use of NSURLSession or some popular third party networking library. Many people makes use of either AFNetworking (Obj-C) or Alamofire (Swift) to make their lives easier and code prettier. You can install both of these through CocoaPods.

The following example will be based on Alamofire, but the code will be very similar for AFNetworking. NSURLSession is a different case, which sometimes is needed in complex multi-threading apps or whenever you wanna provide better background support.

NOTE: This code is simply a demo and is all contained in the same UIViewController which is bad practice. You will need to refactor it yourself into seperate models for better code. Also, the NSDateFormatter in the NSDate extension is highly inefficient. Also, this test makes use of HTTP, so ATS is turned off.

//
//  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)
    } 
}
相关阅读:
Top