Các skill bao gồm tích hợp SDK, xây dựng flow và paywall, kiểm tra trước khi phát hành, di chuyển placement và nhiều hơn nữa. Mô tả công việc bằng ngôn ngữ thường ngày và agent sẽ chọn skill phù hợp.
Làm theo hướng dẫn này để tích hợp bản đồ tương tác vào một flow. Bản đồ hiển thị các địa điểm của bạn, chẳng hạn như các trung tâm thể hình đối tác, trong phạm vi 2 km tính từ vị trí người dùng. Ứng dụng của bạn hiển thị bản đồ dưới dạng native view trong một phần tử tùy chỉnh, sử dụng MapKit trên iOS và MapLibre trên Android. Ứng dụng sẽ yêu cầu quyền truy cập vị trí ngay trên màn hình flow.
Trước khi bắt đầu
Cập nhật ứng dụng lên Adapty Flutter SDK 4.4 trở lên. Các phiên bản SDK cũ hơn sẽ hiển thị nội dung dự phòng cho mọi custom element.
Thiết lập code native trong ứng dụng cho các custom element, theo hướng dẫn Flutter.
Trên iOS, chế độ xem bản đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng sẽ thấy nội dung dự phòng.
Trên iOS, để yêu cầu quyền truy cập vị trí, thêm key NSLocationWhenInUseUsageDescription vào ios/Runner/Info.plist. Đặt giá trị của key này là nội dung thông báo yêu cầu, chẳng hạn như “Find fitness centers near you.”
Trên Android, thêm MapLibre vào ứng dụng bằng Gradle, từ org.maplibre.gl:android-sdk-opengl. Với artifact này, Google Play cũng cung cấp ứng dụng cho các thiết bị không có Vulkan, vốn là yêu cầu của artifact android-sdk mặc định.
Trên Android, đặt minSdk từ 23 trở lên vì MapLibre yêu cầu điều này.
Để giới hạn ứng dụng Android của bạn chỉ sử dụng vị trí gần đúng, hãy thêm đoạn sau vào bên trong phần tử <manifest> của android/app/src/main/AndroidManifest.xml. Đảm bảo rằng phần tử <manifest> đã khai báo xmlns:tools="http://schemas.android.com/tools".
Height: Giữ nguyên chiều cao mặc định Fixed. Bản đồ sẽ lấp đầy phần tử tùy chỉnh.
Đặt phần tử tùy chỉnh ngoài các container phản hồi thao tác chạm, chẳng hạn như carousel, để chỉ bản đồ phản hồi khi người dùng kéo trên nó.
Bên trong phần tử tùy chỉnh, thêm một Image với hình ảnh của bản đồ. Người dùng sẽ thấy nó như là nội dung dự phòng khi:
Phiên bản ứng dụng của họ không hiển thị được bản đồ.
Họ đã từ chối quyền truy cập vị trí trước khi màn hình mở ra.
Thiết bị của họ chạy iOS 16.
Nếu người dùng chưa trả lời lời nhắc quyền truy cập vị trí, ứng dụng sẽ hiển thị lời nhắc đó khi bản đồ xuất hiện. Để cho người dùng biết tại sao ứng dụng cần vị trí của họ, hãy thêm một phần tử văn bản phía trên phần tử tùy chỉnh, ví dụ: “Tìm trung tâm thể dục gần bạn.”
2. Tạo map view
Tạo một kiểu cho các địa điểm và một model cho quyền truy cập vị trí:
// A place of your app, such as a partner fitness centerstruct Place: Identifiable { let id = UUID() let name: String let coordinate: CLLocationCoordinate2D}// One location manager for the resolver and the map view@MainActorfinal class LocationAccess: NSObject, ObservableObject, CLLocationManagerDelegate { @Published private(set) var status: CLAuthorizationStatus = .notDetermined var isMapOnScreen = false private let manager = CLLocationManager() var isDenied: Bool { status == .denied || status == .restricted } override init() { super.init() manager.delegate = self status = manager.authorizationStatus } // Shows the prompt only if the user hasn't answered it yet func requestAccess() { manager.requestWhenInUseAuthorization() } nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { let status = manager.authorizationStatus Task { @MainActor in self.status = status } }}
// a place of your app, such as a partner fitness centerdata class Place(val name: String, val latitude: Double, val longitude: Double)private const val PERMISSION = Manifest.permission.ACCESS_COARSE_LOCATION // approximate location// one location access model for the resolver and the map viewclass LocationAccess(context: Context) { private val appContext = context.applicationContext // checkSelfPermission returns the same value before the first request and after a denial: save the answer private val answers = appContext.getSharedPreferences("location_access", Context.MODE_PRIVATE) private var isAsking = false var isMapOnScreen = false val isAllowed: Boolean get() = ContextCompat.checkSelfPermission(appContext, PERMISSION) == PackageManager.PERMISSION_GRANTED val isDenied: Boolean get() = !isAllowed && answers.getBoolean("denied", false) // requests location access and saves the answer // unregister the returned launcher when the view leaves the screen fun requestAccess(activity: ComponentActivity, onAnswer: (Boolean) -> Unit): ActivityResultLauncher<String> { val isPromptOpen = isAsking // after a screen rotation, this request receives the answer from the open prompt val request = activity.activityResultRegistry.register("location_access", RequestPermission()) { granted -> isAsking = false answers.edit().putBoolean("denied", !granted).apply() onAnswer(granted) } if (!isPromptOpen) { isAsking = true request.launch(PERMISSION) } return request }}// the activity that shows the flowtailrec fun Context.findComponentActivity(): ComponentActivity = this as? ComponentActivity ?: (this as ContextWrapper).baseContext.findComponentActivity()
Tạo một view kèm bản đồ. View này yêu cầu quyền truy cập vị trí và hiển thị một marker cho mỗi địa điểm của bạn trong vòng 2 km tính từ người dùng:
@available(iOS 17.0, *)struct NearbyFitnessCentersMap: View { @ObservedObject var access: LocationAccess let places: [Place] @State private var position: MapCameraPosition = .userLocation(fallback: .automatic) @State private var nearbyPlaces: [Place] = [] var body: some View { ZStack { if access.isDenied { ContentUnavailableView( "Location access is off", systemImage: "location.slash", description: Text("To see fitness centers near you, allow location access in Settings.") ) } else { Map(position: $position) { UserAnnotation() ForEach(nearbyPlaces) { place in Marker(place.name, systemImage: "dumbbell.fill", coordinate: place.coordinate) .tint(.teal) } } .task { access.requestAccess() do { for try await update in CLLocationUpdate.liveUpdates() { guard let location = update.location else { continue } nearbyPlaces = places.filter { place in let placeLocation = CLLocation( latitude: place.coordinate.latitude, longitude: place.coordinate.longitude ) return location.distance(from: placeLocation) <= 2_000 // meters } withAnimation { position = .automatic // zoom to fit the user and the places } break } } catch { // the map still shows the location of the user } } } } // Tells the resolver that the map is on the screen .onAppear { access.isMapOnScreen = true } .onDisappear { access.isMapOnScreen = false } }}
Chế độ xem bản đồ yêu cầu iOS 17 trở lên. Trên iOS 16, người dùng sẽ thấy paywall dự phòng.
// map tiles without an API keyconst val MAP_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"class NearbyFitnessCentersMap( context: Context, private val access: LocationAccess, private val places: List<Place>,) : FrameLayout(context), DefaultLifecycleObserver, LocationEngineCallback<LocationEngineResult> { private val activity = context.findComponentActivity() private val locationEngine = LocationEngineDefault.getDefaultLocationEngine(context) private val mapView: MapView private var permissionRequest: ActivityResultLauncher<String>? = null init { MapLibre.getInstance(context) mapView = MapView(context) mapView.onCreate(null) mapView.getMapAsync { map -> map.setStyle(MAP_STYLE_URL) } addView(mapView) } override fun onAttachedToWindow() { super.onAttachedToWindow() access.isMapOnScreen = true // tells the resolver that the map is on the screen activity.lifecycle.addObserver(this) when { access.isAllowed -> showUser() access.isDenied -> showAccessOff() else -> permissionRequest = access.requestAccess(activity) { granted -> if (granted) showUser() else showAccessOff() } } } override fun onDetachedFromWindow() { access.isMapOnScreen = false permissionRequest?.unregister() locationEngine.removeLocationUpdates(this) activity.lifecycle.removeObserver(this) // the SDK creates a new view each time the custom element appears: release this map mapView.onPause() mapView.onStop() mapView.onDestroy() super.onDetachedFromWindow() } // passes the lifecycle of the activity to the map override fun onStart(owner: LifecycleOwner) = mapView.onStart() override fun onResume(owner: LifecycleOwner) = mapView.onResume() override fun onPause(owner: LifecycleOwner) = mapView.onPause() override fun onStop(owner: LifecycleOwner) = mapView.onStop() @SuppressLint("MissingPermission") // runs only after the user allows location access private fun showUser() = mapView.getMapAsync { map -> map.getStyle { style -> val options = LocationComponentActivationOptions.builder(context, style).locationEngine(locationEngine) map.locationComponent.activateLocationComponent(options.build()) map.locationComponent.isLocationComponentEnabled = true val request = LocationEngineRequest.Builder(1_000).build() // milliseconds between updates locationEngine.requestLocationUpdates(request, this, Looper.getMainLooper()) // calls onSuccess } } // the first location of the user override fun onSuccess(result: LocationEngineResult) { val user = result.lastLocation ?: return locationEngine.removeLocationUpdates(this) showPlaces(user) } override fun onFailure(exception: Exception) = Unit // a teal circle for each of your places within 2 km of the user private fun showPlaces(user: Location) = mapView.getMapAsync { map -> val distance = FloatArray(1) val pins = places.filter { place -> Location.distanceBetween(user.latitude, user.longitude, place.latitude, place.longitude, distance) distance[0] <= 2_000 // meters }.map { place -> Feature.fromGeometry(Point.fromLngLat(place.longitude, place.latitude)) } map.getStyle { style -> style.addSource(GeoJsonSource("places", FeatureCollection.fromFeatures(pins))) val teal = PropertyFactory.circleColor(Color.rgb(0, 128, 128)) style.addLayer(CircleLayer("pins", "places").withProperties(teal, PropertyFactory.circleRadius(8f))) } // zoom in on the area around the user map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(user.latitude, user.longitude), 12.0)) } private fun showAccessOff() { mapView.visibility = GONE addView(TextView(context).apply { text = "Location access is off. To see fitness centers near you, allow location access in Settings." gravity = Gravity.CENTER }) }}
View này tải bản đồ từ OpenFreeMap, một dịch vụ miễn phí không cần API key và không có đảm bảo về uptime. Để chuyển sang nguồn tile khác, hãy thay đổi hằng số MAP_STYLE_URL.
Nếu người dùng từ chối quyền truy cập vị trí trên màn hình, view sẽ thay thế bản đồ bằng thông báo hướng dẫn cách cấp quyền trong Settings.
3. Khớp map với custom element
Trong resolver toàn ứng dụng của bạn, thêm các thuộc tính cho model LocationAccess và các địa điểm. Sau đó trả về map view cho Type map và ID fitness_centers. Các dòng được highlight cho thấy những gì cần thêm hoặc thay đổi. Nếu ứng dụng của bạn chưa có resolver toàn ứng dụng, hãy sao chép toàn bộ code:
struct CustomElementsResolver: AdaptyUICustomElementsResolver { let locationAccess = LocationAccess() let places: [Place] // your app's places, such as partner fitness centers func view( forType type: String, id: String, context: AdaptyUICustomElementContext ) -> AnyView? { switch type { case "map" where id == "fitness_centers": guard #available(iOS 17.0, *) else { return nil // iOS 16: show the fallback } if locationAccess.isDenied, !locationAccess.isMapOnScreen { return nil // access denied before the screen opened: show the fallback } return AnyView(NearbyFitnessCentersMap(access: locationAccess, places: places)) // the other cases of your resolver default: return nil } }}
class CustomElementsResolver( context: Context, private val places: List<Place>, // your app's places, such as partner fitness centers) : AdaptyCustomElementsResolver { private val locationAccess = LocationAccess(context) override fun resolve(type: String, id: String): AdaptyCustomElementContent? = when (type) { "map" -> when (id) { "fitness_centers" -> if (locationAccess.isDenied && !locationAccess.isMapOnScreen) { null // access denied before the screen opened: show the fallback } else { AdaptyCustomElementContent.view( factory = { context, _ -> NearbyFitnessCentersMap(context, locationAccess, places) }, ) } // the other maps of your resolver else -> null } // the other Types of your resolver else -> null }}
SDK gọi resolver khi màn hình mở, và gọi lại mỗi khi vẽ lại phần tử tùy chỉnh trong khi màn hình đang mở. Quyền truy cập vị trí xác định những gì resolver trả về trong mỗi lần gọi:
Chưa trả lời: Chế độ xem bản đồ, để chế độ xem có thể yêu cầu quyền truy cập.
Đã cho phép: Chế độ xem bản đồ, hiển thị các địa điểm của bạn gần người dùng.
Đã từ chối trước khi màn hình mở: Không có chế độ xem, nên người dùng thấy fallback thay vì thông báo về Settings.
Đã từ chối trên màn hình: Chế độ xem bản đồ, vì chế độ xem đặt isMapOnScreen trong khi nó đang hiển thị. Nếu resolver không trả về chế độ xem ở đây, SDK sẽ thay thế thông báo về Settings bằng fallback ở lần gọi tiếp theo.
Tạo resolver với các địa điểm của bạn, và đặt nó làm resolver toàn ứng dụng khi khởi chạy:
Trong ios/Runner/AppDelegate.swift, thêm các import và đặt resolver trong phương thức application(_:didFinishLaunchingWithOptions:). Giữ nguyên phần còn lại của class AppDelegate:
// in application(_:didFinishLaunchingWithOptions:), before `return super.application(...)`// your app's places, such as partner fitness centerslet places = [ Place(name: "Central Fitness", coordinate: CLLocationCoordinate2D(latitude: 52.5219, longitude: 13.4132)), Place(name: "Riverside Gym", coordinate: CLLocationCoordinate2D(latitude: 52.5163, longitude: 13.3777)),]AdaptyUI.setCustomElementsResolver(CustomElementsResolver(places: places))
class App : Application() { // your app's places, such as partner fitness centers val places = listOf( Place("Central Fitness", latitude = 52.5219, longitude = 13.4132), Place("Riverside Gym", latitude = 52.5163, longitude = 13.3777), ) override fun onCreate() { super.onCreate() AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this, places)) }}
Đặt tên cho class App trong android/app/src/main/AndroidManifest.xml, như đã mô tả trong Truyền resolver vào SDK.
Nếu code Dart của bạn tải các địa điểm, hãy lưu chúng trong một store mà code native điền vào thông qua platform channel, giống như công thức biểu đồ mục tiêu cân nặng thực hiện với các giá trị cân nặng.
4. Kiểm tra trên thiết bị
Flow & Paywall Builder không thể chạy mã ứng dụng của bạn, vì vậy canvas chỉ hiển thị fallback. Để xem trước bản đồ:
Xuất bản flow. Để xem phiên bản đã xuất bản mới nhất thay vì phiên bản được lưu trong bộ nhớ đệm, hãy đăng ký thiết bị làm thiết bị kiểm thử.
Để thấy điểm đánh dấu trên bản đồ, hãy thêm một địa điểm trong phạm vi 2 km so với vị trí của bạn vào danh sách địa điểm.
Chạy bản build ứng dụng có bao gồm resolver. Trên iOS, hãy dùng thiết bị chạy iOS 17 trở lên. Mở màn hình và cho phép truy cập vị trí. Xác nhận rằng bản đồ hiển thị vị trí của bạn và điểm đánh dấu cho địa điểm bạn đã thêm.
Để kiểm tra paywall dự phòng, hãy từ chối quyền truy cập vị trí:
iOS: Trong ứng dụng Settings, đi đến Privacy & Security > Location Services > tên app của bạn, và chọn Never. Sau đó mở lại màn hình.
Android: Trong ứng dụng Settings, tắt quyền truy cập vị trí cho app của bạn. Mở màn hình, nếu có hộp thoại xuất hiện thì từ chối quyền truy cập vị trí. Chế độ xem bản đồ sẽ hiển thị thông báo về Settings. Mở lại màn hình và xác nhận rằng paywall dự phòng đã xuất hiện.
Để tìm hiểu lý do tại sao paywall dự phòng xuất hiện thay vì bản đồ, hãy làm theo hướng dẫn trong phần Test on a device của hướng dẫn Flutter.