By making use of WCSession sendMessage, I am getting ErrorDomainCode 7005 constantly within one of my Projects.
I get this error when testing with all simulators and also on real iPhone and paired Apple Watch. Devices are definitely paired.
The exact same code works fine for other (newer) projects that I created from scratch together with a Watch Extension.
I do have this problem only in an older Project where I have added a watch extension recently.
The watch app simply does not communicate with the iPhone app.
Following is my Code:
AppDelegate in didFinishLaunchingWithOptions:
if ([WCSession isSupported]) {
[[WCSession defaultSession] setDelegate:self];
[[WCSession defaultSession] activateSession];
}
AppDelegate: Receiver of Message
- (void)session:(WCSession *)session
didReceiveMessage:(NSDictionary<NSString *, id> *)message
replyHandler:(void (^)(NSDictionary<NSString *, id> *_Nonnull))replyHandler {
replyHandler(#{ #"message" : #"OK" });
}
Watch Extension InterfaceController: awakeWithContext
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
[[WCSession defaultSession] isReachable];
if ([WCSession isSupported]) {
[[WCSession defaultSession] setDelegate:self];
[[WCSession defaultSession] activateSession];
}
[self.wcSession sendMessage:applicationData
replyHandler:^(NSDictionary *reply) {
NSLog(#"OK");
}
errorHandler:^(NSError *error) {
//catch any errors here
[self.testLabel setText:[error.userInfo objectForKey:#"NSLocalizedDescription"]];
}
];
This is what I've tried up to now:
reset content and settings of all simulators
deleted watch app from watch &from iPhone
via settings in Watch App on Phone: Removed Watch Extension for Phone App and reinstalled it
Tried setting up the iPhone WCSession in AppDelegate INIT Method
I am struggling with this issue for many days now. So every hint is highly appreciated.
Related
I have implemented push notification for android and it work 100% correctly but when I open the same app to test push notification for IOS it fails as it requires for a config file here is my config file code:
import { firebase } from '#react-native-firebase/messaging';
const reactNativeFirebaseConfig = {
apiKey: "my apiKey",
...
...
measurementId: "my measurementID XYZ"
};
firebase.initializeApp(reactNativeFirebaseConfig);
now the issue is even after adding this to my project gives an error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()
Note: I am using '#react-native-firebase/app'; and '#react-native-firebase/messaging' for push notification which is working for Android. anyone knows what is wrong on my code side or where should I use that config file as I saved this file as FirebaseConfig.js.
To setup Firebase on iOS, you need to do a few extra steps.
Open Firebase, and create a new iOS app.
Fill in the bundle identifier and give it a nickname of your choice.
Next download the google services file and open xCode.
Drag the Google Services file into the file tree yourApp/yourApp, next to your AppDelegate.m file.
Open AppDelegate.m and add
#import <Firebase.h>
to the top.
Next, at around line 58 there should be a return YES.
Add this above the return
[FIRApp configure];
Lastly, after the return and close bracket, add this code.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
}
All together it should look similar to this.
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[FIRApp configure];
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
}
After you've done that, you should be all set to send your first message to your app.
Bare in mind that Firebase isn't very quick to send messages, it can take a few minutes to come through.
Side-note you cant sent notifications to a iOS simulator, only a real device. You also need to add Notification permission to the app in your Apple developer account, and in xCode.
If you need help setting this up, let me know and we can Skype.
You need to add a check in the following file's method didFinishLuanchWithOptions ios/{AppName}/AppDelegate.m
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
First times doesn't work "Null"( before open App in iPhone )
and some times doesn't work but i want one loop or timer for repeat this request for get result :
here is my code
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
// Temporary fix, I hope.
// --------------------
__block UIBackgroundTaskIdentifier bogusWorkaroundTask;
bogusWorkaroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bogusWorkaroundTask];
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] endBackgroundTask:bogusWorkaroundTask];
});
// --------------------
__block UIBackgroundTaskIdentifier realBackgroundTask;
realBackgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
reply(nil);
[[UIApplication sharedApplication] endBackgroundTask:realBackgroundTask];
}];
// Kick off a network request, heavy processing work, etc.
// Return any data you need to, obviously.
// reply(nil);
reply(#{#"Confirmation" : #"Text was received."});
[[UIApplication sharedApplication] endBackgroundTask:realBackgroundTask];
// NSLog(#"User Info: %#", userInfo);
}
Watch App Code
- (void)willActivate {
// This method is called when watch view controller is about to be visible to user
[super willActivate];
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:#"MyCamande", #"OK", nil];
[InterfaceController openParentApplication:dictionary reply:^(NSDictionary *replyInfo, NSError *error) {
NSLog(#"Reply received by Watch app: %#", replyInfo);
}];
}
how can recall for get finally result
Well, I would not recommend you using anything, related to network operations on watch itself. First of all because Apple does not recommend to do it for obvious reasons. The only network thing that is performed on the watch directly is loading images.
I have been struggling with network operations and watch for like a week and came to a conclusion, that the most stable way to do it right now is not obvious.
The main issue is that WKInterfaceController.openParentApplication(...) does not work as expected. One can not just request to open iPhone app and give back the response as is. There are tons of solutions stating that creating backgound thread in - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply would work just fine, but it actually does not. The problem is that this method has to send reply(...); right away. Even creating synchronious requests won't help, you will keep receiving "error -2 iPhone application did not reply.." like 5 times our of 10.
So, my solution is following:
You implement:
func requestUserToken() {
WKInterfaceController.openParentApplication(["request" : "token"], reply: responseParser)
}
and parse response for error that might occur if there's no response from iPhone.
On iOS side
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
__block UIBackgroundTaskIdentifier watchKitHandler;
watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:#"backgroundTask"
expirationHandler:^{
watchKitHandler = UIBackgroundTaskInvalid;
}];
NSString *request = userInfo[#"request"];
if ([request isEqualToString:#"token"])
{
reply(#{#"token" : #"OK"});
[PSWatchNetworkOperations.shared loginUser];
}
dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1 ), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
[[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
} );
}
This code just creates a background thread that forces iPhone to send a network request. Let's imagine you would have a special class in your iPhone app that would send these requests and send the answer to watch. For now, this is only accomplishable using App Groups. So you have to create an app group for your application and watchkit extension. Afterwards, I would recommend using MMWormhole in order to establish communication between your app and extension. The manual is pretty self-explaining.
Now what's the point of all this. You have to implement sending request to server and send response through wormhole. I use ReactiveCocoa, so example from my code is like this:
- (void)fetchShoppingLists
{
RACSignal *signal = [PSHTTPClient.sharedAPIClient rac_GET:#"list/my" parameters:#{#"limit":#20, #"offset":#0} resultClass:PSShoppingListsModel.class];
[signal subscribeNext:^(PSShoppingListsModel* shoppingLists) {
[self.wormHole passMessageObject:shoppingLists identifier:#"shoppingLists"];
}];
[signal subscribeError:^(NSError *error) {
[self.wormHole passMessageObject:error identifier:#"error"];
}];
}
As you see here I send back either response object, or error. Note, that all that you send through wormhole should be NSCoding-compatible.
Now on the watch you'll probably parse response like this:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
PSWatchOperations.sharedInstance.requestUserToken()
PSWatchOperations.sharedInstance.wormhole.listenForMessageWithIdentifier("token", listener: { (messageObject) -> Void in
// parse message object here
}
})
}
So, to make a conclusion. You send request to parent application to wake up from background and start async operation. Send reply() back immediately. When you receive answer from operation send notification that you've got response. Meanwhile listen to response in your watchExtension.
Sorry, that was a lot of text, but I just hope it helps keep one's ass cool, because I've spent a lot of nerves on that.
May be you can try to explain the exact problem a little more clearly. But one thing you may want to do regardless is to make the openParentApp call in awakeWithContext: instead of willActivate.
I'm trying to use Meteor and this Cordova plugin -https://github.com/don/cordova-plugin-ble-central - added to my project using meteor add cordova in order to connect to a Bluetooth LE device (TI Sensortag). All I want to do to begin with is, when a link is clicked, to connect to the device and show a message.
I have the following code in the events section of my template javascript.
Template.measure.events({'click [data-action=scan-connect-stream]':
function(event, template) {
event.preventDefault();
if (Meteor.isCordova) {
Meteor.startup(function () {
ble.connect('24:09:00:DE:00:42',
function(){
alert('Connect success');
return;
},
function(){
alert('Connect failed');
return;
});
});
}
}
});
My problem is that sometimes the code works and I get a 'Connect success' alert but more often than not it it fails to connect and shows the 'Connect failed' alert. Before I added the return statements in the success and fail callbacks it didn't work at all.
I'm debugging this on an android device (meteor run android-device --verbose) and can see via adb logcat that the BLE Connect event in the Cordova plugin is firing but then doesn't connect. I get the same issue debugging on two different phones and when using a BLE device that isn't a TI Sensortag so I'm guessing this is an problem with the way the plugin is interacting with Meteor (maybe Meteor isn't waiting long enough for a success callback?).
Has anyone used this plugin successfully with Meteor or can anyone provide any clue as to what I'm doing wrong? Should I try wrapping it in a Meteor package or is there any way I can give the plugin more time to respond before the success or fail callbacks fire? Any help would be much appreciated!
For anyone who's having similar issues this is what sorted it for me. I put the ble.connect call into the success callback of the ble.scan function. Not sure why but scanning for a few seconds first does the job.
Template.measure.events({
'click [data-action=scan-connect-stream]': function(event, template) {
event.preventDefault();
if (Meteor.isCordova) {
Meteor.startup(function () {
device_id = '24:09:00:DE:00:42';
ble.scan([], 5,
function(peripherals){
connectDevice(device_id);
},
function(){
alert('No devices found');
}
);
});
}
}
});
var connectDevice = function (device_id) {
ble.connect(device_id,
function(){
alert('Device ' + device_id + ' connnected');
},
function(){
alert('Couldn\'t connect to device ' + device_id);
});
}
If anyone can explain why the ble.connect won't work on its own that'd be great!
EDIT: Looking at the Android code it seems that the plugin is designed in such a way that ble.scan has to be called before calling ble.connect. The ble.scan causes a LinkedHashMap in the Android code to be populated with any discovered devices. Only once the device is listed in the LinkedHashMap can you then connect to it using ble.connect.
My Android app scans BLE devices, and from a certain point it start to fails with error code 2 (ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED). I'm using Nexus 9, 5.0.1 Lollipop.
This problem continued even after I relaunched the app, and when I restarted the Bluetooth service from Settings, I could finally get rid of the problem. But this problem is recurring, and I think I'm coding in a wrong way; BLE related APIs are new and there is few information.
Does anyone know a general solution for this error, preferably not requiring restart of the Bluetooth service? Even though this error code is documented in Android API reference, I don't know how to handle it properly.
When you got the error
SCAN_FAILED_APPLICATION_REGISTRATION_FAILED
You should disable the BluetoothAdapter
BluetoothAdapter.getDefaultAdapter().disable();
Disabling BluetoothAdapter, the event STATE_TURNING_OFF is fired. Once this event is fired, try to reconnect to the BluetoothAdapter:
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "bluetooth adapter turned off");
handler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d(TAG, "bluetooth adapter try to enable");
BluetoothAdapter.getDefaultAdapter().enable();
}}, 500);
break;
It turns out that Bluetooth LE requires the following Android application permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--BLE scanning is commonly used to determine a user's location with Bluetooth LE beacons. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- if your app targets API level 21 or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
<!--app is available to BLE-capable devices only. -->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Besides on main activity:
// onResume()
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_ENABLE_CODE);
}
You should perform operations only success initialization of BT adapter.
To be sure that it is ready create intent filter:
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
and broadcast receiver(you will perform action only if adapter is ready):
val broadcastReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
val action = intent?.action
if (action != null && action == BluetoothAdapter.ACTION_STATE_CHANGED) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
when (state) {
BluetoothAdapter.STATE_ON -> {
if (bluetoothAdapter.isEnabled) {
//perform your task here
}
}
BluetoothAdapter.STATE_OFF -> {}
}
}
}
}
then register receiver:
registerReceiver(broadcastReceiver, filter)
and relaunch adapter(this part can be replaces with check):
bluetoothAdapter.disable()
bluetoothAdapter.enable()
DONE!
I had this happen to me today. While manually disabling and then enabling BT in the Android Settings did not fix this, I was able to get it working after only disabling it manually and then have the app that is affected by the issue enable BT.
The app then pops up an Android System message "An app is requesting permission to turn on BT" (I have a German UI, so it may be worded differently), and when I then press allow, the app finally has proper access to BT and this error no longer shows.
Sounds like a bug or something.
I am working to add a photo ability to my app using Meteor's mdg:camera plugin. For now, I don't have any PhoneGap devices setup, so I am testing on my laptop. I thought I read somewhere that the Meteor implementation would fall-back and use a simple file dialog when a camera wasn't available, but when I try to run the following code on my laptop:
var cameraOptions = {
width: 800,
height: 600
};
MeteorCamera.getPicture(cameraOptions, function (err, data) {
if (err) {
console.log(err);
// TODO Need to handle the error
} else {
if (!this.photos) {
this.photos = [];
}
this.photos.push({ submitted_by: Meteor.userId(), submitted_on: new Date(), photo_data: data});
}
});
I get the error:
Meteor.makeErrorType.errorClass {error: "unknownError", reason: "There was an error while accessing the camera.", details: undefined, message: "There was an error while accessing the camera. [unknownError]", errorType: "Meteor.Error"…}
I would actually like for users to be able to upload photos via the same button when using a laptop. For what it's worth, I actually do have a camera built-in, and I am developing on a 15" MacBook Pro.
On browser client, the mdg:camera falls back on using navigator.getUserMedia to try to obtain a video stream from the webcam, it does not allow the user to upload a photo.
https://github.com/meteor/mobile-packages/blob/master/packages/mdg:camera/photo-browser.js#L41
Unfortunately as we are speaking getUserMedia lacks support on Safari, which is probably the browser you are using working on a MacBook.
http://caniuse.com/#feat=stream
Try your application on Google Chrome or Firefox instead.