【问题标题】:Doesn't show notification after add 'self'添加“自我”后不显示通知
【发布时间】:2017-05-01 13:07:09
【问题描述】:

我在 IOS 中有一个监控用户位置的项目,当他经过他想要的附近时,应用程序会通知他..这是我的代码

import UIKit
import MapKit
import CoreLocation
import UserNotifications
import FirebaseDatabase
import FirebaseAuth

class testingViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!


var users: User?
var todoList = [Todo] ()
let usersRef = FIRDatabase.database().reference(withPath: "Users")
var snapshot: [FIRDataSnapshot]! = []
let locationManager = CLLocationManager()

  override func viewDidLoad() {
    super.viewDidLoad()

    FIRAuth.auth()?.addStateDidChangeListener() { auth, user in

        if user != nil {
            guard let user = user else { return }
            self.users = User(authData: user)
            let currentUserRef = self.usersRef.child((self.users?.uid)!)
            currentUserRef.setValue(self.users?.email)
            print(user.uid)
        } else {
            print("Not signed in")
        }
    }



    // 2. setup locationManager
    locationManager.delegate = self;

    //  self.locationManager = CLLocationManager()
    //   locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    // locationManager.desiredAccuracy = kCLLocationAccuracyBest
    //  locationManager.startMonitoringSignificantLocationChanges()
    //   locationManager.startUpdatingLocation()

    // setup mapView
    mapView.delegate = self
    mapView.showsUserLocation = true
    mapView.userTrackingMode = .follow


    // 4. setup test data
    setupData()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // 1. status is not determined
    if CLLocationManager.authorizationStatus() == .notDetermined {
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
    }

        // 2. authorization were denied
    else if CLLocationManager.authorizationStatus() == .denied {
        print("Location services were previously denied. Please enable location services for this app in Settings.")
    }

        // 3. we do have authorization
    else if CLLocationManager.authorizationStatus() == .authorizedAlways {
        //  locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges();

    }

}


func setupData() {

    let usercur = (FIRAuth.auth()?.currentUser?.uid)!
    let test = FIRDatabase.database().reference(fromURL: "https://ade-mc-trial.firebaseio.com/Data")
    test.child(usercur).child("ToDoList").observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {


    // 1. check if system can monitor regions

    if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {

        // 2. region data
        let title = "medical collage"
        let coordinate = CLLocationCoordinate2DMake(25.900767, 45.3411889)
        let regionRadius = 350.0

        // 3. setup region
        let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude,
                                                                     longitude: coordinate.longitude), radius: regionRadius, identifier: title)


        self.locationManager.startMonitoring(for: region)

        // 4. setup annotation
        let restaurantAnnotation = MKPointAnnotation()
        restaurantAnnotation.coordinate = coordinate;
        restaurantAnnotation.title = "\(title)";
        self.mapView.addAnnotation(restaurantAnnotation)

        // 5. setup circle
        let circle = MKCircle(center: coordinate, radius: regionRadius)
        self.mapView.add(circle)


    }
    else {
        print("System can't track regions")
    }

        }})


}



// 6. draw circle
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.strokeColor = UIColor.blue
    circleRenderer.lineWidth = 1.0
    return circleRenderer

}


// 1. user enter region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    let notification = UILocalNotification()
    notification.fireDate = NSDate(timeIntervalSinceNow: 0) as Date
    notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
    notification.alertAction = "be awesome!"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["CustomField1": "w00t"]
    UIApplication.shared.scheduleLocalNotification(notification)







    /*



     guard let settings = UIApplication.shared.currentUserNotificationSettings else { return }







     if settings.types == .none {



     let ac = UIAlertController(title: "Can't schedule", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .alert)



     ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))



     present(ac, animated: true, completion: nil)



     return



     }*/



}







/* func showAlert(_ title: String) {



 let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)



 alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in



 alert.dismiss(animated: true, completion: nil)



 }))



 self.present(alert, animated: true, completion: nil)







 }*/



 }

但是当我想将它与数据库链接时——firebase——它迫使我更正三行以添加“self”。我在强制我添加“self”的行中添加了星号。然后代码不起作用,并且在添加“self”后没有显示通知

import UIKit
import MapKit
import CoreLocation
import UserNotifications
import FirebaseDatabase
import FirebaseAuth

class testingViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {


@IBOutlet weak var mapView: MKMapView!


var users: User?
var todoList = [Todo] ()
let usersRef = FIRDatabase.database().reference(withPath: "Users")
var snapshot: [FIRDataSnapshot]! = []
let locationManager = CLLocationManager()

  override func viewDidLoad() {
    super.viewDidLoad()

    FIRAuth.auth()?.addStateDidChangeListener() { auth, user in

        if user != nil {
            guard let user = user else { return }
            self.users = User(authData: user)
            let currentUserRef = self.usersRef.child((self.users?.uid)!)
            currentUserRef.setValue(self.users?.email)
            print(user.uid)
        } else {
            print("Not signed in")
        }
    }



    // 2. setup locationManager
    locationManager.delegate = self;

    //  self.locationManager = CLLocationManager()
    //   locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    // locationManager.desiredAccuracy = kCLLocationAccuracyBest
    //  locationManager.startMonitoringSignificantLocationChanges()
    //   locationManager.startUpdatingLocation()

    // setup mapView
    mapView.delegate = self
    mapView.showsUserLocation = true
    mapView.userTrackingMode = .follow


    // 4. setup test data
    setupData()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // 1. status is not determined
    if CLLocationManager.authorizationStatus() == .notDetermined {
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
    }

        // 2. authorization were denied
    else if CLLocationManager.authorizationStatus() == .denied {
        print("Location services were previously denied. Please enable location services for this app in Settings.")
    }

        // 3. we do have authorization
    else if CLLocationManager.authorizationStatus() == .authorizedAlways {
        //  locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges();

    }

}


func setupData() {

    let usercur = (FIRAuth.auth()?.currentUser?.uid)!
    let test = FIRDatabase.database().reference(fromURL: "https://ade-mc-trial.firebaseio.com/Data")
    test.child(usercur).child("ToDoList").observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists() {


    // 1. check if system can monitor regions

    if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {

        // 2. region data
        let title = "medical collage"
        let coordinate = CLLocationCoordinate2DMake(25.900767, 45.3411889)
        let regionRadius = 350.0

        // 3. setup region
        let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude,
                                                                     longitude: coordinate.longitude), radius: regionRadius, identifier: title)


        self.locationManager.startMonitoring(for: region)//*****************

        // 4. setup annotation
        let restaurantAnnotation = MKPointAnnotation()
        restaurantAnnotation.coordinate = coordinate;
        restaurantAnnotation.title = "\(title)";
        self.mapView.addAnnotation(restaurantAnnotation)//***************

        // 5. setup circle
        let circle = MKCircle(center: coordinate, radius: regionRadius)
        self.mapView.add(circle)//*******************************


    }
    else {
        print("System can't track regions")
    }

        }})


}



// 6. draw circle
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let circleRenderer = MKCircleRenderer(overlay: overlay)
    circleRenderer.strokeColor = UIColor.blue
    circleRenderer.lineWidth = 1.0
    return circleRenderer

}


// 1. user enter region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    let notification = UILocalNotification()
    notification.fireDate = NSDate(timeIntervalSinceNow: 0) as Date
    notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
    notification.alertAction = "be awesome!"
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.userInfo = ["CustomField1": "w00t"]
    UIApplication.shared.scheduleLocalNotification(notification)

     }





 }

请问有人有解决办法吗?

【问题讨论】:

  • 你有一个名为 mapView 的函数和一个名为 mapView 的出口

标签: swift firebase notifications firebase-realtime-database location


【解决方案1】:

我认为关闭是不理解self。 一般来说,您应该使用self 的弱引用而不是强引用。尝试创建 self 的弱引用并将其放入闭包中。

代码将更改如下。

func setupData() {
weak var weakSelf = self //Updates
let usercur = (FIRAuth.auth()?.currentUser?.uid)!
let test = FIRDatabase.database().reference(fromURL: "https://ade-mc-trial.firebaseio.com/Data")
test.child(usercur).child("ToDoList").observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.exists() {


// 1. check if system can monitor regions

if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {

    // 2. region data
    let title = "medical collage"
    let coordinate = CLLocationCoordinate2DMake(25.900767, 45.3411889)
    let regionRadius = 350.0

    // 3. setup region
    let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude,
                                                                 longitude: coordinate.longitude), radius: regionRadius, identifier: title)


    weakSelf.locationManager.startMonitoring(for: region)//Updates

    // 4. setup annotation
    let restaurantAnnotation = MKPointAnnotation()
    restaurantAnnotation.coordinate = coordinate;
    restaurantAnnotation.title = "\(title)";

weakSelf.mapView.addAnnotation(restaurantAnnotation)//Updates

    // 5. setup circle
    let circle = MKCircle(center: coordinate, radius: regionRadius)
    weakSelf.mapView.add(circle)//Updates


}
else {
    print("System can't track regions")
}

    }})


  }

【讨论】:

  • 我试试你说的.. 问题没有出现通知没有出现..
  • 为什么你使用locationManager.startMonitoringSignificantLocationChanges(); 定位它应该是locationManager.startUpdatingLocation() 而不是我认为你的func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) 没有调用,因为如果你的应用程序在后台使用位置,你应该允许后台定位来自项目目标中的功能部分以及location if (DEVICEVERSION >= 9.0) {self.locationManager.allowsBackgroundLocationUpdates = YES;} iOS 9 或更高版本代码中的这一行
猜你喜欢
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2012-02-02
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多