Text on BackButton of Navigation - SwiftUI - swiftui

How to change the text of button "back" of the navigationBar on swiftUI?
form from a navigationLink
init(){
UINavigationBar.appearance().backgroundColor = UIColor(named: "azul")
UINavigationBar.appearance().tintColor = UIColor(named: "azul")
UINavigationBar.appearance().barTintColor = UIColor(named: "azul")
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.white]
UITableView.appearance().separatorColor = .clear
}
var body: some View {
NavigationView() {
List {
NavigationLink(destination: CalculoCPKDadosHoffView()) {
FuncionalidadeRow(nome: "Cálculo de CPK - Ciclo total do pneu",
descricao: "Calcula o custo por quilômetro rodado de um pneu e suas recapagens e compara com o concorrente.")
}
NavigationLink(destination: CalculoMMSulcoView()) {
FuncionalidadeRow(nome: "Cálculo mm de sulco - Ciclo total do pneu", descricao: "Calcula o custo por milímetro de sulco de um pneu e compara com o concorrente.")
}
//NavigationLink(destination: TelaTeste()) {
// FuncionalidadeRow(nome: "Tela teste", descricao: "Apenas para fazer testes no app.")
//}
}.navigationBarTitle("Funcionalidades")
}

The NavigationView should take the "Back" text to the text of the navigationBarTitle

Related

Swiftui - Disable Keyboard from showing up for TextField

For swiftui are there anything for disable/prevent keyboard from showing up for TextField?
because I am designing a calculator and getting the input from the design instead of keyboard
You can use UITextField with UIViewRepresentable, which lets you stop the keyboard from showing up.
import SwiftUI
struct KeyboardView: View {
#State var text: String = ""
#State var placHolder: String = "Enter username"
var body: some View {
VStack {
Spacer()
MyTextField(currentText: $text, placeHolder: $placHolder)
.padding(.horizontal, 40.0)
Spacer()
}
}
}
struct MyTextField: UIViewRepresentable {
#Binding var currentText: String
#Binding var placeHolder: String
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.inputView = UIView() // hiding keyboard
textField.inputAccessoryView = UIView() // hiding keyboard toolbar
textField.placeholder = placeHolder
textField.textColor = UIColor.black
textField.font = UIFont.systemFont(ofSize: 22.0)
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ textField: UITextField, context: Context) {
textField.text = currentText
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $currentText)
}
class Coordinator: NSObject, UITextFieldDelegate {
#Binding var text: String
init(text: Binding<String>) {
self._text = text
}
}
}
Reference: Prevent Keyboard from appearing when tapping on UITextField
if you already have a TextField setup, you can add .disabled(true),
this will stop the keyboard from showing up.
TextField("", text: $txt)
.disabled(true) // <--- here

How to manage Scrollview Height according to textview content Swiftui [duplicate]

This question already has an answer here:
How to set width of editable UITextView in SwiftUI ScrollView?
(1 answer)
Closed 6 months ago.
I am trying to manage scrollview height according to textview content height with other view.
Code:
struct TextviewWithScrollview: View {
#State private var textStyle = UIFont.TextStyle.body
#State private var textForTextView = "fdgfhjdsgfdhsgfdsfg dsfg dsfgdsfh fh sf hdsjklf dhsjkfhsdjkfdhsjkfadhsfkds fdshfjkldsh fjkldsh fdshfdshfdsfhsfdsfh sf ewf g iuf herjkdsjkjvdhsvdshvdsv dshv ds vads vds hvsdvjkds vds hviuds vhv disu ghdisuv g"
var body: some View {
ZStack {
Color.red
.ignoresSafeArea()
ScrollView {
VStack(alignment: .leading) {
TextView(isEditable: .constant(false), text: .constant(textForTextView), textStyle:$textStyle, didStartEditing: .constant(false),placeHolderText:"")
}
HStack {
Button("Top") {
}
Button("Middle") {
}
Button("Bottom") {
}
}
}
}
}
}
struct TextView: UIViewRepresentable {
#Binding var isEditable:Bool
#Binding var text: String
#Binding var textStyle: UIFont.TextStyle
#Binding var didStartEditing: Bool
var placeHolderText: String = ""
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isScrollEnabled = true
textView.dataDetectorTypes = .all
textView.textColor = .white
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
}
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
init(_ text: Binding<String>) {
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
DispatchQueue.main.async {
self.text.wrappedValue = textView.text
}
}
}
}
Output without Scrollview:
Output With Scrollview:
Can someone please explain to me how to manage Scrollview Height according to textview content with other's views. I've tried to implement by above but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
If I understand you correctly, this is what you would like to achieve:
To get this result, embed the ScrollView in a GeometryReader and size the TextView with a frame. Like so:
struct TextviewWithScrollview: View {
#State private var textStyle = UIFont.TextStyle.body
#State private var textForTextView = "fdgfhjdsgfdhsgfdsfg dsfg dsfgdsfh fh sf hdsjklf dhsjkfhsdjkfdhsjkfadhsfkds fdshfjkldsh fjkldsh fdshfdshfdsfhsfdsfh sf ewf g iuf herjkdsjkjvdhsvdshvdsv dshv ds vads vds hvsdvjkds vds hviuds vhv disu ghdisuv g"
var body: some View {
ZStack {
Color.red
.ignoresSafeArea()
GeometryReader { geo in
ScrollView {
VStack(alignment: .leading) {
TextView(isEditable: .constant(false), text: .constant(textForTextView), textStyle:$textStyle, didStartEditing: .constant(false),placeHolderText:"")
.frame(width: geo.size.width, height: 300)
}
HStack {
Button("Top") {
}
Button("Middle") {
}
Button("Bottom") {
}
}
}
}
}
}
Here is another solution that adds auto-resizing of the TextView based on the amount of text shown:
And here is the code for that:
class myTextObject: ObservableObject {
#Published var text: String = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem."
}
struct TextviewWithScrollview: View {
#State private var textStyle = UIFont.TextStyle.body
#StateObject var textForView = myTextObject()
#State private var textViewSize: CGSize = CGSize(width: 300, height: 300)
var body: some View {
ZStack {
Color.red
.ignoresSafeArea()
GeometryReader { geo in
ScrollView {
VStack(alignment: .leading) {
TextView(
isEditable: .constant(false),
text: $textForView.text,
textStyle: $textStyle,
didStartEditing: .constant(false),
placeHolderText: "",
textViewSize: $textViewSize
)
.frame(minHeight: 30, idealHeight: min(textViewSize.height, geo.size.height), maxHeight: geo.size.height)
}
HStack {
Button("Top") {
}
Button("Middle") {
self.$textForView.text.wrappedValue += "\n-- a new line --"
}
Button("Bottom") {
}
}
}
}
}
}
}
struct TextView: UIViewRepresentable {
#Binding var isEditable:Bool
#Binding var text: String
#Binding var textStyle: UIFont.TextStyle
#Binding var didStartEditing: Bool
var placeHolderText: String = ""
#Binding var textViewSize: CGSize
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isScrollEnabled = true
textView.dataDetectorTypes = .all
textView.textColor = .gray
DispatchQueue.main.async {
textViewSize = textView.sizeThatFits(textView.textContainer.size)
}
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
DispatchQueue.main.async {
let newContentSize = uiView.sizeThatFits(uiView.textContainer.size)
context.coordinator.parent.$textViewSize.wrappedValue = newContentSize
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: TextView
init(parent: TextView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
DispatchQueue.main.async {
self.parent.$text.wrappedValue = textView.text
let newContentSize = textView.sizeThatFits(textView.textContainer.size)
self.parent.$textViewSize.wrappedValue = newContentSize
}
}
}
}

Simultaneous Gestures not working for a ZoomableScrollView in SwiftUI

Using Swift5.3.2, iOS14.4.1, Xcode12.4,
I am trying to use the .simultaneousGesture modifier in SwiftUI.
As far as I understood, this modifier should make sure that gestures (such as tap, longpress, magnification etc) should be able to co-exist within a View.
In my example I am using a ZoomableScrollView. And it works fine as long as I do not use the simultaneousGesture.
But as soon as I use the extra simultaneousGesture, the ZoomableScrollView is no longer "zoomable" (i.e. none of its gestures work anymore).
What can I do to make the zoom still work AND get an extra dragGesture ?
import SwiftUI
struct MediaTabView: View {
#GestureState private var dragOffset: CGFloat = -100
var body: some View {
ZoomableScrollView {
Image(uiImage: UIImage(contentsOfFile: url.path)!)
.resizable()
.scaledToFit()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.simultaneousGesture(
DragGesture()
.updating($dragOffset) { (value, gestureState, transaction) in
let delta = value.location.x - value.startLocation.x
if delta > 10 { // << some appropriate horizontal threshold here
gestureState = delta
print(delta)
}
}
.onEnded {
if $0.translation.width > 100 {
// Go to the previous slide
print("on ended")
}
}
)
}
}
The code for the ZoomableScrollView is here :
import SwiftUI
struct ZoomableScrollView<Content: View>: UIViewRepresentable {
private var content: Content
init(#ViewBuilder content: () -> Content) {
self.content = content()
}
func makeUIView(context: Context) -> UIScrollView {
// set up the UIScrollView
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator // for viewForZooming(in:)
scrollView.maximumZoomScale = 20
scrollView.minimumZoomScale = 1
scrollView.bouncesZoom = true
// create a UIHostingController to hold our SwiftUI content
let hostedView = context.coordinator.hostingController.view!
hostedView.translatesAutoresizingMaskIntoConstraints = true
hostedView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
hostedView.frame = scrollView.bounds
hostedView.backgroundColor = .black
scrollView.addSubview(hostedView)
return scrollView
}
func makeCoordinator() -> Coordinator {
return Coordinator(hostingController: UIHostingController(rootView: self.content))
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
// update the hosting controller's SwiftUI content
context.coordinator.hostingController.rootView = self.content
assert(context.coordinator.hostingController.view.superview == uiView)
}
// MARK: - Coordinator
class Coordinator: NSObject, UIScrollViewDelegate {
var hostingController: UIHostingController<Content>
init(hostingController: UIHostingController<Content>) {
self.hostingController = hostingController
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return hostingController.view
}
}
}

how to convert an user number in days or hours or seconds swiftUI

I am new in Swift UI, I am trying to convert a value what I get from a textfiled and picker to convert that in days, minutes or seconds, this is from the tutorial 100 days with swiftUI i am lost because I dont understand how do the operations if someone can help me and explain me a little the code please, thank you.
this is my code
struct ContentView: View {
#State private var convertir = 2
let tipConverciones = ["segundos","minutos","horas","dias"]
#State private var convertirselection = 2
let convertirA = ["segundos","minutos","horas","dias"]
#State var cantidadconvertir = ""
var convertidormetodo: Double{
//Funcion que calcula el total de personas
let conteocantidad = Double(cantidadconvertir) ?? 0
let convertirSeleccion = (convertirA)
return 0
}
var body: some View {
NavigationView{
Form {
Section (header: Text("Convertir")) {
Picker ("Convertir de", selection: $convertir){
ForEach(0 ..< tipConverciones.count){
Text("\(self.tipConverciones[$0])")
}//ForEach
}//Picker
.pickerStyle(SegmentedPickerStyle())
}//Seccion3
Section (header: Text("Ingresar Cantidad a convertir")) {
TextField("Ingresa la cuentidad", text: $cantidadconvertir)
.keyboardType(.decimalPad)
}//seccion5
Section (header: Text("Convertir a")) {
Picker ("Convertir de", selection: $convertir){
ForEach(0 ..< tipConverciones.count){
Text("\(self.tipConverciones[$0])")
}//ForEach
}//Picker
.pickerStyle(SegmentedPickerStyle())
}//Seccion4
Section{//seccion 4
Text("La cantidad convertida es: \(convertidormetodo)")
}//seccion 4
}//Form
.navigationBarTitle("Convertidor SwiftUI")
}//Navigation View
}//body
}//view
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
an example of a user input and the desired output would help. But I think what you're looking for is either the dateFormatter or numberFormatter:
https://developer.apple.com/documentation/foundation/dateformatter
https://developer.apple.com/documentation/foundation/numberformatter

Location manager stops updating location

I am having a problem while updating the user location. I am building app which is show the nearest trashcans and the distance between them and the user. I am using this locationmanager but it never updates the location. Even when the user moves, the stored locations stay the same
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
//store myLocation in UserDefaults
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")
UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
UserDefaults().synchronize()
self.mapView.showsUserLocation = true
}
I am using this to calculate the distance
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "longitude") as! CLLocationDegrees)
// geeft zin met afstand van locatie1 tot myLocation
func afstandPuntTotUser(locatie1: CLLocationCoordinate2D) -> String {
manager.startUpdatingLocation()
let cllocatie1 = converter(locatie: locatie1)
let myLocation = converter(locatie: myLocation)
let afstand = cllocatie1.distance(from: myLocation)
let afgerondeafstand = afstand - afstand.truncatingRemainder(dividingBy: 1.0) //zorgt voor 1 kommagetal
if afstand < 1000.0 {
return "De afstand tot de bak is \(afgerondeafstand) meter"
}
else {
return "De afstand tot de bak is \(afgerondeafstand / 1000 - (afgerondeafstand / 1000).truncatingRemainder(dividingBy: 0.1)) kilometer"
}
}
inside the app this isn't a very big problem, but I need a constantly updated location in order for the widget to work properly. This widget shows the three nearest trashcans and doesn't really do what it is supposed to do if it is using old location data.
here is my complete ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations[0]
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
//let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
//let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
//store myLocation in UserDefauls
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")
UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
UserDefaults().synchronize()
//region wel of niet? nog even over hebben
//mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//maakt van CLLocationCoordinate een CLLocation
func converter(locatie: CLLocationCoordinate2D) -> CLLocation {
let latitude = locatie.latitude
let longitude = locatie.longitude
return CLLocation(latitude: latitude, longitude: longitude)
}
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults.standard.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults.standard.value(forKey: "longitude") as! CLLocationDegrees)
//let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "longitude") as! CLLocationDegrees)
// geeft zin met afstand van locatie1 tot myLocation
func afstandPuntTotUser(locatie1: CLLocationCoordinate2D) -> String {
let cllocatie1 = converter(locatie: locatie1)
let myLocation = converter(locatie: myLocation)
let afstand = cllocatie1.distance(from: myLocation)
let afgerondeafstand = afstand - afstand.truncatingRemainder(dividingBy: 1.0) //zorgt voor 1 kommagetal
if afstand < 1000.0 {
return "De afstand tot de bak is \(afgerondeafstand) meter"
}
else {
return "De afstand tot de bak is \(afgerondeafstand / 1000 - (afgerondeafstand / 1000).truncatingRemainder(dividingBy: 0.1)) kilometer"
}
}
//geeft puur afstand van locatie1 tot myLocation
func distanceForWidget(locatie1: CLLocationCoordinate2D) -> String {
let cllocatie1 = converter(locatie: locatie1)
let myLocation = converter(locatie: myLocation)
let afstand = cllocatie1.distance(from: myLocation)
let meters = afstand as Double - afstand.truncatingRemainder(dividingBy: 1.0) as Double
let kilometers = afstand / 1000 - (afstand / 1000).truncatingRemainder(dividingBy: 0.1)
if afstand < 1000.0 {
return "\(meters) m"
}
else {
return "\(kilometers) km"
}
}
//voegt snel een afvalbakpin toe
func addAfvalbak(pinLocatie: CLLocationCoordinate2D) -> MKAnnotation {
return purePin(title: "Afvalbak", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie) as MKAnnotation
}
//voegt sel een glasbakpin toe
func addGlasbak(pinLocatie:CLLocationCoordinate2D) -> MKAnnotation {
return purePin(title: "Glasbak", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie)
}
//voegt snel een blikvangerpin toe
func addBlikvanger(pinLocatie:CLLocationCoordinate2D) -> MKAnnotation {
return purePin(title: "Blikvanger", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie)
}
//voegt snel een volledige afvalbak pin + afstand toe
func addFullAfvalbak(pinlocatie: CLLocationCoordinate2D) -> fullPin {
return fullPin(title: "Afvalbak", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
}
//voegt snel een volledige glasbak pin + afstand toe
func addFullGlasbak(pinlocatie: CLLocationCoordinate2D) -> fullPin {
return fullPin(title: "Glasbak", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
}
//voegt snel een volledige blikvanger pin + afstand toe
func addFullBlikvanger(pinlocatie: CLLocationCoordinate2D) -> fullPin {
return fullPin(title: "Blikvanger", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
}
//array met alle afvalbaklocaties
let afvalbakLocaties: [CLLocationCoordinate2D] = [jacobbotkeweg1, jacobbotkeweg2, jacobbotkeweg3, jacobbotkeweg4, jacobbotkeweg5, jacobbotkeweg6, jacobbotkeweg7, aldlansdyk1, aldlansdyk2, aldlansdyk3, weideflora1, weideflora2, hempensweg1, hempensweg2, hempensweg3, hempensweg4, hempenserweg1, hempenserweg2, hempenserweg3, legedyk1, verlengdeschrans1, oostergoweg1, henridunantweg1, henridunantweg2, henridunantweg3, henridunantweg4, henridunantweg5, henridunantweg6, henridunantweg7, abbingapark1, abbingapark2, tijnjedyk1, tijnjedyk2, tijnjedyk3, tijnjedyk4, ipebrouwerssteeg1, nieuwestad1, nieuwestad2, nieuwestad3, nieuwestad4, nieuwestad5, nieuwestad6, nieuwestad7, nieuwestad8, nieuwestad9, nieuwestad10, nieuwestad11, nieuwestad12]
//array met alle glasbaklocaties
let glasbakLocaties: [CLLocationCoordinate2D] = [timothee1]
//array met alle blikvangerlocaties
let blikvangerLocaties: [CLLocationCoordinate2D] = [bitgummerdyk1]
//slaat alle locaties op voor widget
//UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(afvalbakLocaties, forKey: "afvalbakLocaties")
//UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(glasbakLocaties, forKey: "glasbakLocaties")
//UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(blikvangerLocaties, forKey: "blikvangerLocaties")
//array met alle pinnen die worden toegevoegd
var allePinnen: [MKAnnotation] = []
//voegt alle afvalbakken toe aan allePinnen
for item in afvalbakLocaties {
allePinnen.append(addAfvalbak(pinLocatie: item))
}
//voegt alle glasbakken toe aan allePinnen
for item in glasbakLocaties {
allePinnen.append(addGlasbak(pinLocatie: item))
}
//voegt alle blikvangers toe aan allePinnen
for item in blikvangerLocaties {
allePinnen.append(addBlikvanger(pinLocatie: item))
}
//voegt alle pinnen toe aan de kaart
mapView.addAnnotations(allePinnen)
var fullPinnen:[fullPin] = []
//voegt alle afvalbakken toe aan fullPinnen
for item in afvalbakLocaties {
fullPinnen.append(addFullAfvalbak(pinlocatie: item))
}
//voegt alle glasbakken toe aan fullPinnen
for item in glasbakLocaties {
fullPinnen.append(addFullGlasbak(pinlocatie: item))
}
//voegt alle blikvangers toe aan fullPinnen
for item in blikvangerLocaties {
fullPinnen.append(addFullBlikvanger(pinlocatie: item))
}
//sorteert de bakken in fullPinnen op afstand
fullPinnen.sort {$0.afstand < $1.afstand}
//slaat de 3 dichtsbijzijnde afvalbakken op
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[0].afstand, forKey: "closestpin1afstand")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[0].title, forKey: "closestpin1naam")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[1].afstand, forKey: "closestpin2afstand")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[1].title, forKey: "closestpin2naam")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[2].afstand, forKey: "closestpin3afstand")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[2].title, forKey: "closestpin3naam")
UserDefaults().synchronize()
Create a new class in the same Project and add this code in your new class. Then check whether your didUpdateLocations method will called or not. And let me know whether this code will work for you or not.
#IBOutlet weak var mapView: MKMapView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations[0]
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
//let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
//let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
//store myLocation in UserDefauls
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")
UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
UserDefaults().synchronize()
//region wel of niet? nog even over hebben
//mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to find user's location: \(error.localizedDescription)")
}
Check the following:
Enable background modes and select location updates in you app targets's capabilities section.
Add NSLocationUsageDescription in your app info plist file.
Add Privacy - Location Always Usage Description in your info plist if you will use the location service while the app is in background or not running else add Privacy - Location When In Use Usage Description if you will only use the location service while the user uses your app.