React Native - Kurulum
Bu sayfa React-Native-Related-Digital SDK kurulum klavuzudur.
- 1 Kurulum
- 1.1 Platform Entegrasyonları
- 1.2 Android
- 1.3 iOS
Kurulum
SDK içerisinde ihtiyaç duyulan kütüphaneyi kurun
npm install @react-native-async-storage/async-storageya da
yarn add @react-native-async-storage/async-storage
Alttaki komutu çalıştırarak React-Native-Related-Digital SDK’sını kurun
npm install react-native-related-digitalya da
yarn add react-native-related-digital
Pod’ları yükleyin (Sadece IOS)
Alttaki komut satırlarını sırasıyla çalıştırın
cd ios
pod install
SDK yüklemesi tamamlandıktan sonra kodları alttaki şekilde uygulamanıza ekleyin.
appAlias değeri iOS ve Android uygulamalar için farklı gönderilmelidir (Expo uygulamalar hariç)
Örnek;
const appAlias = Platform.OS === "ios" ? "RelatedStoreIOS" : "RelatedStoreAndroid";
RMC ekibinden alias, SID, OID ve datasource değerlerinizi istemeyi unutmayın.
import {
addEventListener,
removeEventListener,
requestPermissions,
EuroMessageApi,
VisilabsApi,
setApplicationIconBadgeNumber,
logToConsole,
RDStoryView,
RecommendationAttribute,
RecommendationFilterType
} from 'react-native-related-digital'
const appAlias = 'alias' // RMC ekibinden isteyiniz.
const siteId = "SID" // RMC ekibinden isteyiniz.
const organizationId = "OID" // RMC ekibinden isteyiniz.
const dataSource = "datasource" // RMC ekibinden isteyiniz.
const visilabsApi = new VisilabsApi(appAlias, siteId, organizationId, dataSource)
const euroMessageApi = new EuroMessageApi(appAlias)Platform Entegrasyonları
Android
Bir Firebase projesi oluşturun. Size verilen Google-services.json dosyasını
android/appklasörü altına kopyalayın. Örnek kullanımAlttaki satırı
android/build.gradledosyanızın iki repositories bölümüne de ekleyin.mavenCentral() maven { url 'http://developer.huawei.com/repo/' allowInsecureProtocol = true }android/build.gradledosyanızın dependencies bölümüne aşağıdaki satırları ekleyin. Örnek kullanımclasspath 'com.google.gms:google-services:4.3.14' classpath 'com.huawei.agconnect:agcp:1.6.5.300'minSdkVersion21 olarak ayarlayıncompileSdkVersionvetargetSdkVersion32 olarak ayarlayı.android/app/build.gradledosyanızın en altına aşağıdaki satırları ekleyin. Örnek kullanımapply plugin: 'com.google.gms.google-services' apply plugin: 'com.huawei.agconnect'android/app/build.gradledosyanızdadefaultConfigbölümüne alttaki satırı ekleyinmultiDexEnabled true
Uygulama ön plandayken bildirim almak için
AndroidManifest.xmldosyanızınapplicationbölümüne aşağıdaki kodu ekleyin.<service android:name="euromsg.com.euromobileandroid.service.EuroFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
Geofence özelliğini etkinleştirmek için
AndroidManifest.xmldosyanıza aşağıdaki kodu ekleyin.<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <service android:name="com.visilabs.gps.geofence.GeofenceTransitionsIntentService" android:enabled="true" android:permission="android.permission.BIND_JOB_SERVICE" /> <receiver android:name="com.visilabs.gps.geofence.VisilabsAlarm" android:exported="false" /> <receiver android:name="com.visilabs.gps.geofence.GeofenceBroadcastReceiver" android:enabled="true" android:exported="true" />Sdk’yı çalıştırmak için alttaki init kodunu
MainApplication.javadosyanıza ekleyin.
Geofence özelliğini etkin hale getirmek içinVisilabs.CreateAPIfonksiyonunun son parametresini(12.)truedeğeri girin.import com.visilabs.Visilabs; import euromsg.com.euromobileandroid.EuroMobileManager;@Override public void onCreate() { // ... initEuroMessage(); } private void initEuroMessage() { String appAlias = "demo-alias"; String huaweiAppAlias = "demo-alias-huawei"; String organizationId = "OID"; String siteId = "SID"; String datasource = "datasource"; String channel = "Android"; String segmentUrl = "http://lgr.visilabs.net"; String realtimeUrl = "http://rt.visilabs.net"; String targetUrl = "http://s.visilabs.net/json"; String actionUrl = "http://s.visilabs.net/actjson"; String geofenceUrl = "http://s.visilabs.net/geojson"; Visilabs.CreateAPI(organizationId, siteId, segmentUrl, datasource, realtimeUrl, channel, this, targetUrl, actionUrl, 30000, geofenceUrl, true, "reactnative"); EuroMobileManager euroMobileManager = EuroMobileManager.init(appAlias, huaweiAppAlias, this); euroMobileManager.setPushIntent("com.demo.MainActivity", this); euroMobileManager.setNotificationLargeIcon(R.drawable.ic_launcher,this); euroMobileManager.setNotificationTransparentSmallIcon(R.drawable.ic_launcher, this); }
Not: setNotificationTransparentSmallIcon fonksiyonuna atayacağınız icon tek katmanlı bir görsel formatı olmalıdır.
setNotificationTransparentSmallIcon ve setNotificationLargeIcon ile ilgili detaylı bilgiye buradan ulaşabilirsiniz.
Yüklü uygulamaları raporlamak istiyorsanız alttaki kodu javascript bölümünde çalıştırın.
await visilabsApi.sendTheListOfAppsInstalled()
Ayrıca alttaki yöntemlerden birini seçipAndroidManifest.xmldosyanıza ekleyin.
Option 1<manifest package="com.example.myApp"> <queries> <package android:name="com.example.app1" /> <package android:name="com.example.app2" /> </queries> </manifest>Option 2
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" ignore="QueryAllPackagesPermission" />
iOS
Push Notifications ve Background Modes->Remote Notifications özelliklerini etkinleştirin.
AppDelegate.hdosyanıza alttaki satırı ekleyin. Örnek kullanım#import <UserNotifications/UNUserNotificationCenter.h>
AppDelegate.hdosyanızdaki @interface ile başlayan satıra UNUserNotificationCenterDelegate parametresini ekleyin. Son hali alttaki gibi olmalı. Örnek kullanım
Klasik React Native projelerinde@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>Expo projelerinde
@interface AppDelegate : UMAppDelegateWrapper <RCTBridgeDelegate, EXUpdatesAppControllerDelegate, UNUserNotificationCenterDelegate>AppDelegate.mdosyanıza alttaki satırları ekleyin. Örnek kullanım#import "RelatedDigitalPushModule.h" #import <UserNotifications/UserNotifications.h>AppDelegate.mdosyanızdadidFinishLaunchingWithOptionsmethodunun içerisindekireturnifadesinin hemen üzerine alttaki satırları ekleyin. Örnek kullanımUNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self;AppDelegate.mdosyanıza alttaki methodları ekleyin. Örnek kullanım- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [RelatedDigitalPushModule didRegisterUserNotificationSettings:notificationSettings]; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [RelatedDigitalPushModule didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [RelatedDigitalPushModule didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [RelatedDigitalPushModule didFailToRegisterForRemoteNotificationsWithError:error]; } -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge); }AppDelegate.mdosyasındakididFinishLaunchingWithOptionsfonksiyonununun return ifadesinden hemen öncesine alttaki kodu ekleyin.
Not: In App ve Geofence özelliklerinin aktif olması içinInAppNotificationsEnabledvegeofenceEnabledparametreleritrueolmalıdır.
Başlangıçta konum izninin alınmasını istemiyorsanızaskLocationPermmissionAtStartparametresinifalseolarak ayarlayın. ArdındanrequestLocationPermission()işleviyle istediğiniz zaman izin talep edebilirsiniz.[RelatedDigitalPushModule initRelatedDigital:@"organization_id" profileId:@"profile_id" dataSource:@"datasource" appAlias:@"app_alias" inAppNotificationsEnabled:true requestTimeoutSeconds:30 geofenceEnabled:true askLocationPermmissionAtStart:true maxGeofenceCount:20 isIDFAEnabled:true loggingEnabled:true];SDK Swift kodu içerdiğinden ve xcode her hedefte en az bir boş swift dosyası gerektirdiğinden projenizin ios dizinine boş bir swift dosyası ekleyin.
Empty.swiftiOS 14 ve sonraki sürümlerde AdvertisingTrackingID'yi kullanabilmek için
Info.plistdosyanızaNSUserTrackingUsageDescriptionekleyin.Eğer
_swift_getFunctionReplacementveya herhangi bir swift hatasından dolayı sorun yaşarsanız, projenizinLibrary Search Pathsaltındaki$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME
satırını kaldırın.In-App Message kullanacaksanız proje hedefinizin
Build Phases->Copy Bundle Resourcesbölümüne aşağıdaki satırları ekleyin.Create folder referencesseçeneğini seçin.Pods/VisilabsIOS/Sources/TargetingAction/InAppNotification/Views/VisilabsMiniNotificationViewController.xib Pods/VisilabsIOS/Sources/TargetingAction/InAppNotification/Views/VisilabsFullNotificationViewController.xib Pods/VisilabsIOS/Sources/TargetingAction/sideBar/sideBarView.xibGörsel veya video gibi zengin içerikli push bildirim özelliklerini etkinleştirmek için alttaki adımları uygulayın.
1- Projenize Targets altındanNotification Service Extensionekleyin ve isminiRelatedDigitalNotificationServiceolarak değiştirin. Ardından bu hizmetin hedef iOS sürümünü 10.0 olarak değiştirin. Örnek kullanım
2- Yeni eklenmiş olanNotificationService.mdosyasının içerisini alttakilerle değiştirin.
Örnek kullanım#import "NotificationService.h" #import "RelatedDigitalNotificationService.h" @interface NotificationService () @property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver); @property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent; @end @implementation NotificationService - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; [RelatedDigitalNotificationService didReceiveNotificationRequest:@"APP_ALIAS" withBestAttemptContent:self.bestAttemptContent withContentHandler:self.contentHandler]; } - (void)serviceExtensionTimeWillExpire { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. [RelatedDigitalNotificationService didReceiveNotificationRequest:@"APP_ALIAS" withBestAttemptContent:self.bestAttemptContent withContentHandler:self.contentHandler]; } @end
3- Podfile dosyanızın kök seviyesine aşağıdaki satırları ekleyin. Örnek kullanımtarget 'RelatedDigitalNotificationService' do pod 'react-native-related-digital', :path => '../node_modules/react-native-related-digital' use_native_modules! end # Post Install processing for RelatedDigitalNotificationService causing errors def notification_service_post_install(installer) installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO' end end end
4- Podfile dosyanızın ana hedef bölümünenotification_service_post_install(installer)satırını ekleyin, alttaki şekilde gözükmeli. Örnek kullanımpost_install do |installer| notification_service_post_install(installer) # Other post install function calls end
5- Sdk, Swift kodu içerdiğinden ve xcode her hedefte en az bir boş swift dosyası gerektirdiğinden, RelatedDigitalNotificationService hedefinize de boş bir swift dosyası ekleyin.Empty.swift
6- Projenizin ios dizinindepod installkomutunu çalıştırın.Carousel push bildirim için
1- Projenize Targets altındanNotification Content Extensionekleyin ve isminiRelatedDigitalNotificationContentolarak değiştirin. Ardından bu hizmetin hedef iOS sürümünü 11.0 olarak değiştirin.Info.plistdışındaRelatedDigitalNotificationContentaltına yeni eklenen dosyaları kaldırın. Ardından aşağıdaki içeriğe sahipEMNotificationViewController.swiftdosyasını ekleyin.import UIKit import UserNotifications import UserNotificationsUI import Euromsg @objc(EMNotificationViewController) class EMNotificationViewController: UIViewController, UNNotificationContentExtension { let carouselView = EMNotificationCarousel.initView() var completion: ((_ url: URL?, _ bestAttemptContent: UNMutableNotificationContent?) -> Void)? var notificationRequestIdentifier = "" func didReceive(_ notification: UNNotification) { notificationRequestIdentifier = notification.request.identifier Euromsg.configure(appAlias: "APP_ALIAS", launchOptions: nil, enableLog: true) carouselView.didReceive(notification) } func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) { carouselView.didReceive(response, completionHandler: completion) } override func loadView() { completion = { [weak self] url, bestAttemptContent in if let identifier = self?.notificationRequestIdentifier { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier]) UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { notifications in bestAttemptContent?.badge = NSNumber(value: notifications.count) }) } if let url = url { if #available(iOSApplicationExtension 12.0, *) { self?.extensionContext?.dismissNotificationContentExtension() } self?.extensionContext?.open(url) } else { if #available(iOSApplicationExtension 12.0, *) { self?.extensionContext?.performNotificationDefaultAction() } } } carouselView.completion = completion carouselView.delegate = self self.view = carouselView } } /** Add if you want to track which carousel element has been selected */ extension EMNotificationViewController: CarouselDelegate { func selectedItem(_ element: EMMessage.Element) { // Add your work... print("Selected element is => \(element)") } }
2- Yeni eklenenRelatedDigitalNotificationContent/Info.plistdosyanıza alttaki satırları ekleyin, eğer varsa değiştirin.<key>NSExtension</key> <dict> <key>NSExtensionAttributes</key> <dict> <key>UNNotificationExtensionUserInteractionEnabled</key> <true/> <key>UNNotificationExtensionDefaultContentHidden</key> <false/> <key>UNNotificationExtensionCategory</key> <string>carousel</string> <key>UNNotificationExtensionInitialContentSizeRatio</key> <real>1</real> </dict> <key>NSExtensionPrincipalClass</key> <string>RelatedDigitalNotificationContent.EMNotificationViewController</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.usernotifications.content-extension</string> </dict>
3- Podfile dosyanızın kök seviyesine alttaki satırları ekleyin.target 'RelatedDigitalNotificationContent' do use_native_modules! pod 'Euromsg', '>= 2.0.0' end
4- Xcode'daRelatedDigitalNotificationContenthedefini seçin. Aşağıdaki dosyalarıBuild Phases->Copy Bundle Resourcesbölümüne ekleyin.Create folder referencesseçeneğini seçin.Pods/Euromsg/Sources/Euromsg/Classes/EMNotificationCarousel/CarouselCell.xib Pods/Euromsg/Sources/Euromsg/Classes/EMNotificationCarousel/EMNotificationCarousel.xib
5- Deployment target değerini ios 10 yapın.platform :ios, '10.0'
6- Projenizin ios dizinindepod installkomutunu çalıştırın.Geofence konum hizmetleri tanımlamaları
Uygulamanızda konum hizmetlerini etkinleştirmek için öncelikle aşağıdaki anahtarları Info.plist dosyanıza eklemeniz gerekir.
- NSLocationAlwaysAndWhenInUseUsageDescription
- NSLocationWhenInUseUsageDescription
Bu izinlerin örnek uygulaması aşağıdaki gibidir:<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>We need access to your location for better user experience.</string> <key>NSLocationWhenInUseUsageDescription</key> <string>We need access to your location for better user experience.</string>
Ayrıca bölgeleri izlemek, bölge listesini yenilemek ve push bildirimlerini almak için Info.plist dosyanızda UIBackgroundModes altına aşağıdaki anahtarları eklemeniz gerekir.<array> <string>fetch</string> <string>location</string> <string>remote-notification</string> </array>
Copyright 2020 Related Digital