- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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)
}
}
请问谁有解决办法?
最佳答案
我认为闭包不理解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")
}
}})
}
关于swift - 添加 'self' 后不显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43719589/
让我们写一个简单的类在我的脑海中解释: class SomeClass { var happyToUsed = 10 } 并创建一个对象 let someObject = SomeClass(
采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别? 例如 impl SomeStruct { fn example1(self) { } fn ex
请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 se
backbone.js 开始于: //Establish the root object, `window` (`self`) in the browser, or `global` on the s
做的事: self = self.init; return self; 在 Objective-C 中具有相同的效果: self.init() 快速? 例如,在这种情况下: else if([form
我查看了关于堆栈溢出的一些关于使用[weak self]和[unowned self]的问题的评论。我需要确保我理解正确。 我正在使用最新的 Xcode - Xcode 13.4,最新的 macOS
我面临在以下模型类代码中的 self.init 调用或分配给 self 之前使用 self 的错误tableview单元格项目,它发生在我尝试获取表格单元格项目的文档ID之后。 应该做什么?请推荐。
晚上好。 我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。 有一个示例函数。 func exampleFunction() { functionWithEsca
我需要在内心深处保持坚强的自我。 我知道声明[weak self]就够了外封闭仅一次。 但是guard let self = self else { return }呢? ,是否也足以为外部闭包声明一
代码 use std::{ fs::self, io::self, }; fn rmdir(path: impl AsRef) -> io::Result { fs::remo
我检查了共享相同主题的问题,但没有一个解决我遇到的这种奇怪行为: 说我有一个简单的老学校struct : struct Person { var name: String var age:
我应该解释为什么我的问题不是重复的:TypeError: can only concatenate list (not “str”) to list ...所以它不是重复的,因为该帖子处理代码中出现的
我有一个 trait,它接受一个类型参数,我想说实现这个 trait 的对象也会符合这个类型参数(使用泛型,为了 Java 的兼容性) 以下代码: trait HandleOwner[SELF
这个问题在这里已经有了答案: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 个答案) 关闭 8
我总是找到一些类似的代码newPromise.promiseDispatch.apply(newPromise, message),我不明白为什么不使用newPromise.promiseDispat
我看到类似的模式 def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... 非
mysql查询示例: SELECT a1.* FROM agreement a1 LEFT JOIN agreement a2 on a1.agreementType = a2.agreementTy
self.delegate = self; 这样做有什么问题吗?正确的做法是什么? 谢谢,尼尔。 代码: (UITextField*)initWith:(id)sender:(float)X:(flo
为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。
这个问题已经有答案了: What does the ampersand (&) before `self` mean in Rust? (1 个回答) 已关闭去年。 我不清楚 self 之间有什么区别
我是一名优秀的程序员,十分优秀!