I made a sample of how to write delegate in SwiftUI 2.0 using MapKit

TL;DR I made a sample delegate using SDK etc. written in Objective-C with reference to CoreLocation. Click here for the source> https://github.com/dropcontrol/LocationUpdata I also use @ ObservableObject and @ObserbedObject instead of @State as a method using Property Wrapper of SwiftUI. Actually, since Property is changed in a single View, @State is enough. When using @ ObservableObject, it means that Property needs to be changed across multiple Views. reference: https://rusutikaa.github.io/docs/developer.apple.com/documentation/swiftui/managing-model-data-in-your-app.html https://capibara1969.com/2508/

How to write a delegate?

The app itself is a single-function app that uses MapKit to get the latitude and longitude and display it. And, the part to get the latitude and longitude is done by func locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {, which is defined in CLLocationManagerDelegate. So how do you write a delegate?

struct ContentView: View {
    
    @ObservedObject var placeInfo = PlaceInfo()
    
    var manager = CLLocationManager()
    var managerDelegate = locationDelegate()
    

    var body: some View {
        
        
        VStack{

            HStack {
                Text("Latitude:")
                Text(placeInfo.latitude)
            }
            HStack {
                Text("longitude:")
                Text(placeInfo.longitude)
            }
            Button(action: {
                print("Button Tapped")
                
                placeInfo.latitude = managerDelegate.currentLatitude
                placeInfo.longitude = managerDelegate.currentLongitude

            }){
                Text("Current Location")
            }
        }
        .onAppear() {
            manager.delegate = managerDelegate
            managerDelegate.locationManagerDidChangeAuthorization(manager)

        }
    }
}

As

You can now access the managerDelegate.locationManagerDidChangeAuthorization (manager) inside the Button and the managerDelegate.locationManagerDidChangeAuthorization (manager) in .onAppear ().

The delegate itself is described as follows.

class locationDelegate : NSObject, ObservableObject, CLLocationManagerDelegate {
    
    //Variables to retrieve from delegate
    var currentLatitude: String = "none"
    var currentLongitude: String = "none"
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {

        if manager.authorizationStatus == .authorizedWhenInUse {
            print("authorized")
            
            manager.startUpdatingLocation()

            // add "Privacy - Location Default Accuracy Reduced" in info.plist
            // and edit in souce code that value is <true/> or <false/>
            if manager.accuracyAuthorization != .fullAccuracy {
                print("reduce accuracy")

                // add "Privacy - Location Temporary Usage Description Dictionary" in info.plist
                // and set "Location" in Key
                manager.requestTemporaryFullAccuracyAuthorization(withPurposeKey: "Location") {
                    (err) in
                    if err != nil {
                        print(err!)
                        return
                    }
                }
            }
        } else {
            print("not authorized")
            // add "Privacy - Location When In Use Usage Description" in info.plist
            manager.requestWhenInUseAuthorization()
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            print(String(format: "%+.06f", location.coordinate.latitude))
            print(String(format: "%+.06f", location.coordinate.longitude))
            
            currentLatitude = String(format: "%+.06f", location.coordinate.latitude)
            currentLongitude = String(format: "%+.06f", location.coordinate.longitude)
            
        }
    }
}

The above managerDelegate.locationManagerDidChangeAuthorization (manager) is a method of CoreLocationg that alerts the user to license the location information (the location information cannot be obtained unless it passes there). Defined in func locationManagerDidChangeAuthorization (_ manager: CLLocationManager) {}. At what level and how do you get permission to acquire information by setting in info.plist? You can set the.

The following func locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {} is used to update the location information. This is the delegate function. In fact, this function isn't called from anywhere, it's called every time the location is updated.

@ ObservableObject and @ObserbedObject

As I wrote briefly, there is no problem writing Property Wrapper with @State in this app (I also commented it out in the source), but with @ ObservableObject, it is @Publised By attaching to a variable, the update is automatically reflected, the variable is shared across multiple views, and it is applied in one place.

How to write

@ObservableObject is defined as a class as follows.

class PlaceInfo: ObservableObject {
    @Published var latitude: String = "none"
    @Published var longitude: String = "none"
}

If you mistakenly type @ ObservedObject in automatic storage here, an error will occur (obviously, it tends to be done).

When using ...

@ObservedObject var placeInfo = PlaceInfo() //This is Observed.

You can instantiate it with and then call it and rewrite variables by doing something like placeInfo.latitude. I personally think that this is a cleaner way to write than writing with @State. It doesn't look like it's problematic to use in a single view, but if you want to manage the scope of variables, it's a good idea to use them properly.

Recommended Posts

I made a sample of how to write delegate in SwiftUI 2.0 using MapKit
I tried to make a sample program using the problem of database specialist in Domain Driven Design
Delegate pattern between views. I also made a sample page transition using NavigationLink.
How to write a date comparison search in Rails
How to write a core mod in Minecraft Forge 1.15.2
I want to find a relative path in a situation using Path
[Beginner] I made a program to sell cakes in Java
I tried to make a client of RESAS-API in Java
I made a simple MVC sample system using Spring Boot
I made a Dockerfile to start Glassfish 5 using Oracle Java
[Java] I want to write asynchronous processing using Promise in Java-Trial of Promise-like grammar of JavaScript-
[Rails] How to write in Japanese
How to write a ternary operator
I tried to write code like a type declaration in Ruby
I made a gem to post the text of org-mode to qiita
How to output a list of strings in JSF as comma-separated strings
I got stuck trying to write a where in clause in ActiveRecord
I made a tool to output the difference of CSV file
How to execute a contract using web3j
I tried to make a parent class of a value object in Ruby
How to sort a List using Comparator
[Rails] I want to send data of different models in a form
I want to write a nice build.gradle
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Basic] How to write a Dockerfile Self-learning ②
How to insert a video in Rails
Summary of how to write annotation arguments
[Introduction to Java] How to write a Java program
I want to write a unit test!
[Java] How to get to the front of a specific string using the String class
How to change the value of a variable at a breakpoint in intelliJ
How to get the absolute path of a directory running in Java
I tried to make a talk application in Java using AI "A3RT"
How to publish a library in jCenter
[SpringBoot] How to write a controller test
I made a bulletin board using Docker 1
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
Creating a sample program using the problem of a database specialist in DDD Improvement 2
Basics of Java development ~ How to write a program (flow and conditional branching) ~
How to get the ID of a user authenticated with Firebase in Swift
[Rails] How to get rid of flash messages in a certain amount of time
Creating a sample program using the problem of a database specialist in DDD Improvement 1
How to make a unique combination of data in the rails intermediate table
I made a primality test program in Java
JDBC promises and examples of how to write
Rails: How to write a rake task nicely
[JavaFX] How to write Eclipse permissions in build.gradle
[Rails] How to write when making a subquery
[Rails] How to create a graph using lazy_high_charts
How to display a web page in Java
How to delete a controller etc. using a command
Write to a file using ShiftJIS-Read a file (Kotlin / JVM)
[Ethereum] How to execute a contract using web3j-Part 2-
I want to simply write a repeating string
How to run a djUnit task in Ant
I made a rock-paper-scissors game in Java (CLI)
I made a Docker container to run Maven
I made a Ruby extension library in C
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP