2017-03-26 68 views
0

我一直在阅读苹果开发者的资源,了解位置更新如何工作以及读取堆栈溢出问题。我试图让我的用户在我的应用程序的位置,所有的时候,用户把应用程序在后台。下面的代码不是我的代码,我发现它来自另一个堆栈溢出源问题,它是唯一让我接近我需要的东西。下面的代码工作和更新我的用户位置只有25分钟,然后只是停止,但我想要的是它始终工作,只要该应用程序在后台:(。这个问题已答复,但我'我听说苹果会在3分钟左右自动终止你的应用程序,所以无论如何绕过这将有助于。我也有我的背景模式检查,如位置更新和背景获取甚至还需要info.plist,这是所说的假设自动唤醒我的应用程序,一旦终止,但似乎也没有工作,如果任何人都可以帮助我这将是一个巨大的帮助,我的新应用程序,这是我需要aha的代码的最后一点,预先感谢大家。还想做到这一点,没有添加一个无声的音频文件,所以我的应用程序不会被拒绝:)在后台连续快速运行应用程序

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.locationManager.requestAlwaysAuthorization() 

    self.locationManager.requestWhenInUseAuthorization() 

    self.locationManager.allowsBackgroundLocationUpdates = true 

     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.startUpdatingLocation() 

    var timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "updateLocation", userInfo: nil, repeats: true) 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ 

    if UIApplication.sharedApplication().applicationState == .Active { 

    } else { 
     backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({() -> Void in 
      self.backgroundTimer.invalidate() 
      self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true) 
     }) 
    } 
} 

func updateLocation() { 

    var timeRemaining = UIApplication.sharedApplication().backgroundTimeRemaining 

    print(timeRemaining) 

    if timeRemaining > 60.0 { 
      print("timeRemaining > 60.0") 
     } 
    } else { 
     if timeRemaining == 0 { 
      print("timeRemaining = 0") UIApplication.sharedApplication().endBackgroundTask(backgroundTaskIdentifier) 
     } 

     backgroundTaskIdentifier2 = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({() -> Void in 
      self.backgroundTimer.invalidate() 
      self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true) 
     }) 
    } 
} 
+0

你为什么要这样做?无论何时移动500.0米,您都可以更新用户的位置。除非用户移动距离,否则他的位置将保持不变。 – Rikh

+0

我的应用程序需要知道他们在任何时候的应用程序的主要目的:) –

回答

1

您不能(目前)不断在后台运行应用程序。这就是苹果计划的事情,你必须接受这一点。一旦你的应用程序处于后台,它可以在任何时候被核心操作系统终止。

+0

任何想法如何instagram,snapchat等发送通知时,当用户收到一个DM或在一条消息Snapchat? –

+0

甚至苹果给出的应用程序映射如何在背景中永远运行在后台? –

+0

苹果应用程序可能(可能)免于“无法在后台规则中无限期运行” - Apple可以用自己的应用程序做任何他们想做的事情:) Instagram和Snapchat通知可能由中央服务器处理,因为消息必须去通过服务器,服务器将向相关用户发送推送通知 - 与持续在后台运行不同。 – Fahim