Only one pin appears on the map - Swift - swift

The user is pinning more than one on the map. I just want the last pin to be displayed, can you help with this?
#objc func selectPin(mapGesture : UILongPressGestureRecognizer) {
if mapGesture.state == .began {
let touchPoint = mapGesture.location(in: self.mapview)
let touchCoordinates = self.mapview.convert(touchPoint, toCoordinateFrom: self.mapview)
choosenLatitude = touchCoordinates.latitude
choosenLongtitude = touchCoordinates.longitude
let annotation = MKPointAnnotation()
annotation.coordinate = touchCoordinates
annotation.title = forWhatText.text
if forWhatText.text == "" {
makeAlert(titleInput: "Error", messageInput: "Please fill in all the fields above!")
} else if phoneName.text == "" {
makeAlert(titleInput: "Error", messageInput: "Please fill in all the fields above!")
} else if phoneNumber.text == "" {
makeAlert(titleInput: "Error", messageInput: "Please fill in all the fields above!")
} else if messageText.text == "" {
makeAlert(titleInput: "Error", messageInput: "Please fill in all the fields above!")
} else {
mapview.addAnnotation(annotation)
//saveButton.isEnabled = true
}
}
}

Instead of adding pin in mapGesture.state == .began use mapGesture.state == .ended

Related

Enable copy button title on long press on the button

I have UIButton for an address in my tableview cell. When I tap on it once; I open google map with the direction no problem. Now, I want to provide the option for long gesture so if you hold your finger on the button, it provides the option to copy the address which is in the title of the button. This is my code:
#IBOutlet weak var addressBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
addLongPressGesture()
}
#objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
// how do I make it possible to copy the title of the button here? The address is already inserted as the title of the button
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 0.5
self.addressBtn.addGestureRecognizer(longPress)
}
This is where on one tap it goes to the map with no problem; so I have no issue here but just fyi:
#IBAction func addressClicked(_ sender: Any) {
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
let street = order.street.replacingOccurrences(of: " ", with: "+")
let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")
if street == "" || order.city == "" || order.province == "" || postalCode == ""{
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
} else {
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
}
} else {
NSLog("Can't use comgooglemaps://")
}
}
Use
let text = addressBtn.currentTitle
or
let text = addressBtn.titleLabel?.text
I figured it out with the following code:
//Create the AlertController and add Its action like button in Actionsheet
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheetControllerIOS8.view.tintColor = AppColors.Blue
let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton = UIAlertAction(title: "Open Google Map", style: .default)
{ _ in
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
let street = order.street.replacingOccurrences(of: " ", with: "+")
let postalCode = order.postalCode.replacingOccurrences(of: " ", with: "+")
if street == "" || order.city == "" || order.province == "" || postalCode == ""{
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=\(order.longitude),\(order.latitude)&directionsmode=driving")! as URL)
} else {
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=&daddr=+\(street),+\(order.city),+\(order.province),+\(postalCode)&directionsmode=driving")! as URL)
}
} else {
NSLog("Can't use comgooglemaps://")
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton = UIAlertAction(title: "Copy Address", style: .default)
{ _ in
let address = "\(order.street), \(order.city), \(order.province), \(order.postalCode)"
let pasteBoard = UIPasteboard.general
pasteBoard.string = address
}
actionSheetControllerIOS8.addAction(deleteActionButton)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}

Set a global variable from within GeoCoder function Swift

I have a global variable "filterError" that is initially set to false before a switch statement. When the switch statement occurs, it will go through a dictionary, and for each key it will do a unique logic check on the value. If that value does not match certain criteria then the Boolean variable filterError will be set to true.
When the switch statement is complete, if filterErrror is false then the an action will occur like so:
//...switch statement...
if (filterErrror == false) {
//do something.....
}
The issue I am having is with the geocoder function which is a case in the switch statement. If the switch variable key = "area" then the below is executed:
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,let location = placemarks.first?.location
else { print("Error in finding location") return }
let distanceInMeters = location.distance(from: coordinateSelf)
print("The distance between property and user in miles is: \(distanceInMeters/1609)")
distanceInMiles = distanceInMeters/1609
var radius = Double()
if searchRadius == "this area only" {
radius = 0.49999999999
} else {
radius = Double(Int(searchRadius)!)
}
if (radius < distanceInMiles) {
filterError = true
}
}
However, the filterError is still false after the switch statement has completed because the boolean value is not being changed. How do you set filterError to true from inside the geocoder?
This is the full code:
for filter in self.activeFilters {
switch filter.key {
case "listingType":
if(filter.value[0] != propertiesFirestore[i]["listingType"]![0]){
filterError = true
}
case "minBedsBound":
if(filter.value[0] != "No min. beds") {
if(filter.value[0].filter("01234567890.".contains) > propertiesFirestore[i]["bedroomCount"]![0]) {
filterError = true
}
}
case "maxBedsBound":
if(filter.value[0] != "No max. beds") {
if(Int(filter.value[0].filter("01234567890.".contains))! < Int(propertiesFirestore[i]["bedroomCount"]![0])!) {
filterError = true
}
}
case "minPriceBound":
if(filter.value[0] != "No min. price") {
if(Int(filter.value[0].filter("01234567890.".contains))! > Int(propertiesFirestore[i]["price"]![0])!) {
filterError = true
}
}
case "maxPriceBound":
if(filter.value[0] != "No max. price") {
if(Int(filter.value[0].filter("01234567890.".contains))! < Int(propertiesFirestore[i]["price"]![0])!) {
filterError = true
}
}
case "includeSharedOwnership":
if(filter.value[0] != propertiesFirestore[i]["sharedOwnership"]![0]) {
filterError = true
}
case "includeRetirementHomes":
if(filter.value[0] != propertiesFirestore[i]["retirementHome"]![0]) {
filterError = true
}
case "area":
print(userlatitude)
print(userlongitude)
let address = "\(propertiesFirestore[i]["area"]![0]), \(propertiesFirestore[i]["postcodePrefix"]![0])"
var propLat = String()
var propLong = String()
var distanceInMiles = Double()
var searchRadius = self.activeFilters["searchRadius"]![0]
let coordinateSelf = CLLocation(latitude: Double(userlatitude) as! CLLocationDegrees, longitude: Double(userlongitude) as! CLLocationDegrees)
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else {
print("Error in finding location")
return
}
let distanceInMeters = location.distance(from: coordinateSelf)
print("The distance between property and user in miles is: \(distanceInMeters/1609)")
distanceInMiles = distanceInMeters/1609
var radius = Double()
if searchRadius == "this area only" {
radius = 0.49999999999
} else {
radius = Double(Int(searchRadius)!)
}
if (radius < distanceInMiles) {
filterError = true
}
}
case "keywords":
print("Filter keywords are: \(filter.value)")
for j in 0..<propertiesFirestore[i]["keywords"]!.count {
propertiesFirestore[i]["keywords"]![j] = propertiesFirestore[i]["keywords"]![j].lowercased()
}
for keyword in filter.value {
if propertiesFirestore[i]["keywords"] == nil {
filterError = true
} else if ((propertiesFirestore[i]["keywords"]!.contains(keyword.lowercased()))) {
print("found keyword")
} else {
filterError = true
}
}
default:
print("Unknown filter: \(filter.key)")
}
}
if filterError == false {
filterProperties.append(propertiesFirestore[i])
} else {
print("FITLER CATCHOUT")
}

Hide action buttons on Lock Screen Mode - iOS Notification Swift 4.2

I want to hide these action buttons during Lock Screen Mode.
Is there a way to detect that in iOS ?
if action == "allow.action" {
APIService.shared.updateCpeDeviceACL(cpe: cpe,vlan: vlan, device: deviceMac ?? "", portalUrl: "", acl: true, caller: self)
if(alertId != nil){
APIService.shared.deleteAlert(id: alertId ?? "", caller: self)
} else {
print("alertId = nil detetected !")
}
if(notificationType != "new-device"){
if(quarantineId != nil){
APIService.shared.allowDeviceToNetwork(id: quarantineId ?? "", caller: self)
} else {
print("quarantineId = nil detetected !")
}
}
} else if action == "delete.action" {
APIService.shared.deleteAlert(id: alertId ?? "", caller: self)
} else if action == "block.action" {
APIService.shared.updateCpeDeviceACL(cpe: cpe,vlan: vlan, device: deviceMac ?? "", portalUrl: "", acl: false, caller: self)
if(alertId != nil){
APIService.shared.deleteAlert(id: alertId ?? "", caller: self)
} else {
print("alertId = nil detetected !")
}
if(notificationType != "new-device"){
if(quarantineId != nil){
APIService.shared.denyDeviceToNetwork(id: quarantineId ?? "", caller: self)
} else {
print("quarantineId = nil detetected !")
}
}
} else {
awakeFromNotification = true
}
How would one go about debugging this further?
I guess you are referring to actionable notifications? If so somewhere in your code you should be able to see:
UNUserNotificationCenter.current().setNotificationCategories([someCategory])
When the someCategory (whatever name used in your app) was created it should receive those actions as a parameter. You can modify them there.

Confusion about setting a optional variable

I want to add the option for a user to add their phone number. If they add any phone number I want to add an alert informing them if they have not added a valid 10 digit phone number. However if they do not add anything in the phone number field I want the phoneInput variable to be set to "0". How would I go about doing this.
var phoneInput = ""
func signUp(){
if profileImage.image == nil {
showAvatarError()
} else if phoneNumber.text == "" {
self.phoneInput = "0"
} else if (phoneNumber.text?.characters.count)! != 10 {
showphoneNumberError()
}else if email.text == "" {
showEmailError()
}else if isValid(email.text!) != true{
showEmailError()
} else{
submitPressed()
print("Set info")
}
}
I'm not sure why you get the result that you do but here is a cleaner version
var phoneInput = ""
func signUp(){
// This check doesn't have anything to do with the number, so separe it
if profileImage.image == nil {
showAvatarError()
return
}
guard let temp = planEndValue.text else {
return
}
let userInput = temp.trimmingCharacters(in: .whitespaces)
if userInput.count == 0 {
self.phoneInput = "0"
} else if userInput.count != 10 {
showphoneNumberError()
}
}

How do you update a users profile settings using firebase and swift?

I am trying to update a users email and full name. This is my code:
func saveTapped() {
var performSegue = false
if updateEmail.text == "" && updateFullName.text == "" {
self.cleanUrCodeRohan("Please fill in one or more of the missing text fields that you would like to update.")
}
if updateEmail.text != "" {
let user = FIRAuth.auth()?.currentUser
user?.updateEmail(updateEmail.text!) { error in
self.ref.child("users").child(self.currentUser).child("email").setValue(self.updateEmail.text!)
}
let emailUpdateRef = FIRDatabase.database().reference().child(currentUser).child("email")
print(emailUpdateRef)
emailUpdateRef.setValue(self.updateEmail.text)
performSegue = true
}
if updateFullName.text != "" {
let user = FIRAuth.auth()?.currentUser
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = self.updateFullName.text!
}
performSegue = true
}
if performSegue == true {
self.navigationController!.popViewControllerAnimated(true)
}
}
I am able to update the email under authorization but not under the database. Any help would be appreciated.
If JSON tree is something like this:-
appName{
users :{
userID :{
email : "..",
username : ".."
}
}
}
Use this Code to update your node's child value's:-
func saveTapped(){
if ((updateEmail.text != "" || updateFullName.text != "") && (updateEmail.text != nil || updateFullName.text != nil)){
let userRef = FIRDatabase.database().reference().child("users").child(FIRAuth.auth()!.currentUser!.uid)
if let new_Email = updateEmail.text as? String{
FIRAuth.auth()!.currentUser!.updateEmail(updateEmail.text!) { error in
if error == nil{
userRef.updateChildValues(["email" : new_Email ], withCompletionBlock: {(errEM, referenceEM) in
if errEM == nil{
print(referenceEM)
}else{
print(errEM?.localizedDescription)
}
})
}
}else{
self.cleanUrCodeRohan("Email couldn't be updated in auth")
}
}
if let new_Name = updateFullName.text as? String{
userRef.updateChildValues(["username" : new_Name ], withCompletionBlock: {(errNM, referenceNM) in
if errNM == nil{
print(referenceNM)
}else{
print(errNM?.localizedDescription)
}
})
}
}else{
self.cleanUrCodeRohan("Please fill in one or more of the missing text fields that you would like to update.")
}
}