Create local location based notifications in swift

后端 未结 2 448
一向
一向 2021-02-04 21:28

I\'m a relatively new swift developer and I\'ve heard in iOS 8 you can send local notifications based on a users Location. I have had a look at some code, particularly this one

相关标签:
2条回答
  • 2021-02-04 21:50

    I found a few guides that had different ways of approaching this, you need to import CoreLocation then you'll want to register the CLLocationManagerDelegate in the ViewController function in ViewController.swift.

    You'll need to get permission for using the location with

    locationManager.delegate = self
    locationManager.requestAlwaysAuthorization()
    UIApplication.sharedApplication().cancelAllLocalNotifications()
    

    If you use the requestWhenInUseAuthorization instead it won't display the notifications as they only are displayed when you are not in the app. In iOS 8 it requires you to declare NSLocationAlwaysUsageDescription in the info.plist file you'll just enter some text to appear when location access is requested.

    Once you've done all of that you can start creating your notifications, you can use the following code to do that

    let locattionnotification = UILocalNotification()
    locattionnotification.alertBody = "You have entered a high risk zone (Crown Range Road) , proceed with caution"
    locattionnotification.regionTriggersOnce = false
    locattionnotification.region = CLCircularRegion(circularRegionWithCenter: CLLocationCoordinate2D(latitude:
        37.33182, longitude: -122.03118), radius: 100.0, identifier: "Location1")
    UIApplication.sharedApplication().scheduleLocalNotification(locattionnotification)
    

    The regionTriggersOnce option allows you to turn on and off if you get multiple messages when you enter and exit the zone or only one when you first enter the area.

    You can change the latitude, longitude and radius (in meters) values to what you want and when you get within the radius of the point you will be alerted with the contents of the message.

    For more details about the different options have a look at https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/

    0 讨论(0)
  • 2021-02-04 21:50

    The SetSDK allows you to set this up really really simply now. Basically, just a few lines of code.

    SetSDK.instance.onDeparture(from: .any) { departed in
        /* do your Swift things here */
       let departureCoordinates = departed.location
       // keep going
    }
    
    SetSDK.instance.onArrival(to: .any) { arrived in
        /* do your Swift things here */
       let arrivalCoordinates = arrived.location
       // keep going
    }
    

    The SDK handles doing the persistent location collection without killing your battery and the locations that it sends notifications for are continuously being learned, so no manual entry of geofences or anything like that. Just start it and go.

    0 讨论(0)
提交回复
热议问题