How to integrate IBM worklight with react-native app? - react-native

Our team was using Ionic/Cordova with IBM worklight(7.0). Recently we got an opportunity to try out react-native and we need the worklight integrated with the application.
How do we integrate IBM worklight with react-native application?

In general you need you to create a React Native project like any other, and add to it the MobileFirst Native iOS SDK as you also would add it to any other native iOS project (by following these instructions: https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.0/hello-world/configuring-a-native-ios-with-the-mfp-sdk/)
You can find detailed instrustions and a video in the following blog post: https://mobilefirstplatform.ibmcloud.com/blog/2015/06/03/react-native/
The blog post does mention an important aspect of the integration to take note of:
Below I think one of the more important chunks of code to integrate React Native for iOS with the MobileFirst Platform Foundation. The code chunk is the MobileFirst Platform Foundation Adapter invocation call from the file ResourceRequest.m being exported into the React Native javascript code. In this section of code there are two important React Native methods. One being RCT_EXPORT_MODULE(); which will allow you to export a native class into the React Native javascript. The other is RCT_EXPORT_METHOD(...) this class explicitly tells React to expose this class's method for use in the React Native javascript. Exporting the particular method below is going to pass in a path named "path" and also a callback named "results." The adapter call is getting a list of movies stored as JSON data to a particular path (this path ended up not being needed). Then that data is passed as the callback into the React Native code.
#import <Foundation/Foundation.h>
#import "WLResourceRequest.h"
#import "ResourceRequest.h"
#implementation ResourceRequest
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(getJavaAdapter:(NSString *)path results:(RCTResponseSenderBlock)callback)
{
NSLog(#"Invoking GET Procedure...");
NSURL* url = [NSURL URLWithString:#"http://localhost:10080/HelloMobileFirst/adapters/MoviesAdapter/getStories"];
WLResourceRequest* resourceRequest = [WLResourceRequest requestWithURL:url method:WLHttpMethodGet];
[resourceRequest sendWithCompletionHandler:^(WLResponse *response, NSError *error) {
NSString* resultText;
if(error != nil){
resultText = #"Invocation failure.";
resultText = [resultText stringByAppendingString: error.description];
}
else{
resultText = response.responseText;
callback(#[[NSNull null], resultText]);
}
}];
}
#end

Related

Recover token from A0SimpleKeychain (from Objective-C to Flutter app)

We have a native iOS version done in Objective-c and we have developed a new version of this app in Flutter. This new Flutter version has a plugin created in Objective-c to get Realm data from native app (old version) and imported to the new Flutter version. And this works!!
Now we want to add the ability to get the token of the old app (using A0SimpleKeychain) and save it in the new one (using Flutter Secure Storage package).
We have this code but A0SimpleKeychain returns null:
// Get the current token stored in keychain
- (NSString *) getCurrentToken {
A0SimpleKeychain *keychain = [[A0SimpleKeychain alloc] initWithService:#"Auth0"];
NSString *token = #"";
token = [[A0SimpleKeychain keychain] stringForKey:#"auth0-user-jwt"];
NSLog(#"TOKEN = %#", token);
return token;
}
Any ideas?

Cocoa get current running path of SIMBL Plugin

I am working on a SIMBL Plugin that is loaded by a 3rd-party host application on macOS. It is almost entirely written in C++ and has only minimal objective-c components. (The UI is largely provided by API calls into the host app.) One of the requirements is that the plugin bundle can be loaded multiple times from different sub-directories. It is a Lua interpreter, and the goal is for each instance to host a different configuration of lua scripts that appear in separate menus on the host application. Third parties could bundle this plugin with a custom configuration for their script(s) and they would appear as separate items in the app's plugin menu.
This issue I have is this: I need to find out what directory my plugin is executing in. I could create a special class called MY_BUNDLE_ID_CLASS and use:
[NSBundle bundleForClass:[MY_BUNDLE_ID_CLASS class]];
Once I have the correct NSBundle, getting the file path is trivial.
The problem is that if multiple instances of my bundle are loaded (from different folders), Cocoa complains that the class MY_BUNDLE_ID_CLASS is defined in multiple locations and won't guarantee me which one was used. For other similar classes this would be fine for my plugin, because my unique class names are macros that equate to a mangled name that includes the version number, but in this case it isn't okay. It would potentially be multiple instances of the same version. Is there any other way to find out the folder my plugin code is executing from? It seems like a simple request, but I am coming up empty. I welcome suggestions.
Given an address in an executable, the dladdr function can be used to query the dynamic linker about the dynamically-linked image containing that address; i.e., given a reference to a symbol in your plugin, dladdr can give you the dynamic linking information about your plugin.
The runtime lookup can look as follows:
// Sample: BundleClass.m, the principal class for the plugin
#import "BundleClass.h"
#import <dlfcn.h>
// We'll be using a reference to this variable compiled into the plugin,
// but we can just as easily use a function pointer or similar -- anything
// that will be statically compiled into the plugin.
int someVariable = 0;
#implementation BundleClass
+ (void)load {
Dl_info info;
if (dladdr(&someVariable, &info) != 0) {
NSLog(#"Plugin loaded from %s", info.dli_fname);
} else {
// Handle lookup failure.
}
}
#end
Instead of &someSymbol, you can also use a reference to a function (e.g. &someFunctionDefinedInThePlugin), but you should be careful not to pass in a pointer that could be dynamically allocated — since that will likely either fail, or point you to the memory space of the host process.
On my machine, with a trivial macOS host app setup, the following loading code:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:#"DynamicBundle" withExtension:#"bundle"];
if (!bundleURL) {
NSLog(#"Failed to find bundle!");
return;
}
NSLog(#"Bundle class before loading: %#", NSClassFromString(#"BundleClass"));
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
NSError *error = nil;
if (![bundle loadAndReturnError:&error]) {
NSLog(#"Failed to load bundle: %#", error);
return;
}
NSLog(#"Bundle class after loading: %#", NSClassFromString(#"BundleClass"));
}
successfully produces
Bundle class before loading: (null)
Loaded plugin from /Volumes/ExtSSD/Developer/Xcode/DerivedData/HostApp/Build/Products/Debug/HostApp.app/Contents/Resources/DynamicBundle.bundle/Contents/MacOS/DynamicBundle
Bundle class after loading: BundleClass
which is indeed the path to the plugin on disk.

How can I import salesforce marketing cloud in ios (react native)

https://github.com/salesforce-marketingcloud/react-native-marketingcloudsdk
How can I import salesforce marketing cloud in ios
After npm install and pod install, when I put the below code in AppDelegate.m
MarketingCloudSDKConfigBuilder *mcsdkBuilder = [MarketingCloudSDKConfigBuilder new];
[mcsdkBuilder sfmc_setApplicationId:#"{MC_APP_ID}"];
[mcsdkBuilder sfmc_setAccessToken:#"{MC_ACCESS_TOKEN}"];
[mcsdkBuilder sfmc_setAnalyticsEnabled:#(YES)];
[mcsdkBuilder sfmc_setMarketingCloudServerUrl:#"{MC_APP_SERVER_URL}"];
NSError *error = nil;
BOOL success =
[[MarketingCloudSDK sharedInstance] sfmc_configureWithDictionary:[mcsdkBuilder sfmc_build]
error:&error];
It show some error regarding Use of undeclared identifier.
Like Use of undeclared identifier 'mcsdkBuilder'
Thanks
Documentation from Salesforce is incomplete, you need to add these two imports:
#import <MarketingCloudSDK/MarketingCloudSDK.h>
#import <MarketingCloudSDK/MarketingCloudSDKConfigBuilder.h>

React Native NativeModules Empty Object

Trying to create my first npm module in order to determine if a user is on the phone. It's for a React Native app. No matter what I try, the module returns undefined. NativeModules always appears to be an empty object.
Please help! Below is a link to the code. export default RNOnPhoneCall; in index.js will only return undefined. How do I link the functions in ios folder, and export them in index.js? Heads up, android is not up to date yet, only ios.
Link to Github
After snooping around a little, I found out that the Obj-C file isn't added to the Compile Sources in Xcode. Just follow me:
Let's say the file names are: NotchNative.h and NotchNative.m. If the NotchNative.m file is not listed, the files will not be compiled by Xcode hence it needs to be added to the Compile Sources.
Follow the steps in the image and rebuild/run the iOS app again.
It's surely a fault on the Xcode side, as it doesn't happen in case of Swift projects.
Try rebuilding your project. I faced the same issue recently and simply rebuilding resolved it
I was not exporting the method correctly in my iOS file. Here's the solution, along with a link to the final project.
react-native-check-phone-call-status on github
#import "RNCheckPhoneCallStatus.h"
#import "React/RCTLog.h"
#import <AVFoundation/AVAudioSession.h>
#import<CoreTelephony/CTCallCenter.h>
#import<CoreTelephony/CTCall.h>
#implementation RNCheckPhoneCallStatus
RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(get:(RCTResponseSenderBlock)callback)
{
NSString *phoneStatus = #"PHONE_OFF";
CTCallCenter *ctCallCenter = [[CTCallCenter alloc] init];
if (ctCallCenter.currentCalls != nil)
{
NSArray* currentCalls = [ctCallCenter.currentCalls allObjects];
for (CTCall *call in currentCalls)
{
if(call.callState == CTCallStateConnected)
{
phoneStatus = #"PHONE_ON";
}
}
}
callback(#[[NSNull null], phoneStatus]);
}
#end

twitpic API GSTwitPicEngine error while setAccessToken

I tried to use GSTwitPicEngine class https://github.com/Gurpartap/GSTwitPicEngine for sharing image on twitter
but its giving error
As we have to set [twitpicEngine setAccessToken:token];
if I am right, I am using _accessToken of class SA_OAuthTwitterEngine as token
_accessToken was private in class SA_OAuthTwitterEngine, I set it to public and also
#property (nonatomic, readonly) OAToken *accessToken;
#synthesize accessToken = _accessToken;
and then in action
twitPicEngine = [GSTwitPicEngine twitpicEngineWithDelegate:self];
[twitPicEngine setAccessToken:twitterObj.accessToken];
[twitPicEngine uploadPicture:[shareDict objectForKey:#"image"] withMessage:[shareDict objectForKey:#"image_msg"]];
But Application getting crash while setAccessToken with log
-[OAToken parameters]: unrecognized selector sent to instance 0x6327e30
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[OAToken parameters]: unrecognized selector sent to instance 0x6327e30'
Please help if you able to find any thing wrong
Amit Battan
Unfortunately, GSTwitPicEngine is not using the same version of oauth-consumer than the fabulous Twitter+Oauth library (SAOAuthTwitterEngine). I assume you are using that library for posting messages to twitter.
The crash is because OAToken from Twitter+Oauth doesn´t implement the "parameters" method.
Today I spent the entire morning tweaking the several libraries to avoid crashes.
Here you can download a sample project I created for posting a twitpic photo to twitter with a message.
TestTwitpic
The project has all the latest versions of all libraries from github.
Instructions for making my TestTwitpic project work:
In TestTwitpic-Prefix.pch set the variables for:
#define kTwitterOAuthConsumerKey #""
#define kTwitterOAuthConsumerSecret #""
#define kTwitPicAPIKey #""
In RootViewController you can change these lines to your needs. To change the photo:
//change [UIImage imageNamed:#"image.jpg"] for whatever UIImage you want to upload
//change #"my photo" for whatever title you want for your photo in twitpic website
[twitpicEngine uploadPicture:[UIImage imageNamed:#"image.jpg"] withMessage:#"my photo"];
and this one to change message sent to twitter:
//I post to twitter the title of the photo and the twitpic url but you can post whatever you want
[engine sendUpdate:[NSString stringWithFormat:#"%# %#", [[[response objectForKey:#"request"] userInfo] objectForKey:#"message"], [[response objectForKey:#"parsedResponse"] objectForKey:#"url"]]];
If you want to create your own project based on this sample. Do the following:
Import into your project (drag and drop) the Twitpic folder with all the libraries that are inside.
Add these frameworks to your project:
CoreGraphics
libz.1.2.3
libxml2
MobileCoreServices
SystemConfiguration
CFNetwork
Security
In Build Settings add "$SDKROOT/usr/include/libxml2" to the "Header Search Paths" (mark it as recursive)
In Build Settings add -lxml2 to "Other linker flags"
If you want to know what I did for fixing the libraries, I will tell you more or less what I remember I did:
Import Twitter+Oauth, GSTwitPicEngine, OARequestHeader, TouchJSON, and ASIHTTPRequest libraries.
Set GSTwitPicEngine to use TouchJSON instead of YAJL.
Added the category NSString+URLEncoding from oauth-consumer github project as OARequestHeader was missing it.
Modified all occurrences of NSDictionary* foo = [toke parameters] inside OARequestHeader with the line:
NSDictionary *foo = [NSDictionary dictionaryWithObject:[token key] forKey:#"oauth_token"];
Created a method getAccessToken in SAOAuthTwitterEngine to return the private _accessToken variable.
In requestFinished: inside GSTwitPicEngine
change the line:
response = [[CJSONDeserializer deserializer] deserialize:responseString error:&error];
with the line:
response = [[CJSONDeserializer deserializer] deserialize:[responseString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
as GSTwitPicEngine wrongly assumed deserialize:error: method accepts an NSString instead of an NSData.
You can set Access token & Access Secret for twitpic after getting from twitter engine i.e
SA_OAuthTwitterEngine.m
(void) setAccessToken: (OAServiceTicket *) ticket withData: (NSData *) data
Create object of "GSTwitPicEngine.m" class in "SA_OAuthTwitterEngine.m" & pass Access token & Access Secret to "GSTwitPicEngine.m" and set delegate methods of "GSTwitPicEngine.m" in "SA_OAuthTwitterEngine.m"
And one more change...
must cross check URLEncoding while genrating OAuth Header i.e
[requestHeader generateRequestHeaders]
this will be according to "OAuthConsumer" classes in Twitter Library