Merge pull request #5784 from BlueWallet/watch

FIX: Apple Watch app not working #5470
This commit is contained in:
GLaDOS 2023-10-31 08:20:16 +00:00 committed by GitHub
commit 7c9dd99183
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 75 additions and 53 deletions

3
App.js
View file

@ -26,7 +26,6 @@ import loc from './loc';
import { BlueDefaultTheme, BlueDarkTheme } from './components/themes'; import { BlueDefaultTheme, BlueDarkTheme } from './components/themes';
import InitRoot from './Navigation'; import InitRoot from './Navigation';
import BlueClipboard from './blue_modules/clipboard'; import BlueClipboard from './blue_modules/clipboard';
import { isDesktop } from './blue_modules/environment';
import { BlueStorageContext } from './blue_modules/storage-context'; import { BlueStorageContext } from './blue_modules/storage-context';
import WatchConnectivity from './WatchConnectivity'; import WatchConnectivity from './WatchConnectivity';
import DeviceQuickActions from './class/quick-actions'; import DeviceQuickActions from './class/quick-actions';
@ -387,8 +386,8 @@ const App = () => {
<InitRoot /> <InitRoot />
<Notifications onProcessNotifications={processPushNotifications} /> <Notifications onProcessNotifications={processPushNotifications} />
</NavigationContainer> </NavigationContainer>
{walletsInitialized && !isDesktop && <WatchConnectivity />}
</View> </View>
<WatchConnectivity />
<DeviceQuickActions /> <DeviceQuickActions />
<Biometric /> <Biometric />
<WidgetCommunication /> <WidgetCommunication />

View file

@ -1,11 +1,11 @@
import { useContext, useEffect, useRef } from 'react'; import React, { useContext, useEffect, useRef } from 'react';
import { import {
updateApplicationContext, updateApplicationContext,
watchEvents, watchEvents,
useReachability, useReachability,
useInstalled, useInstalled,
usePaired,
transferCurrentComplicationUserInfo, transferCurrentComplicationUserInfo,
transferUserInfo,
} from 'react-native-watch-connectivity'; } from 'react-native-watch-connectivity';
import { Chain } from './models/bitcoinUnits'; import { Chain } from './models/bitcoinUnits';
import loc, { formatBalance, transactionTimeToReadable } from './loc'; import loc, { formatBalance, transactionTimeToReadable } from './loc';
@ -18,14 +18,13 @@ function WatchConnectivity() {
const { walletsInitialized, wallets, fetchWalletTransactions, saveToDisk, txMetadata, preferredFiatCurrency } = const { walletsInitialized, wallets, fetchWalletTransactions, saveToDisk, txMetadata, preferredFiatCurrency } =
useContext(BlueStorageContext); useContext(BlueStorageContext);
const isReachable = useReachability(); const isReachable = useReachability();
const isPaired = usePaired();
const isInstalled = useInstalled(); // true | false const isInstalled = useInstalled(); // true | false
const messagesListenerActive = useRef(false); const messagesListenerActive = useRef(false);
const lastPreferredCurrency = useRef(FiatUnit.USD.endPointKey); const lastPreferredCurrency = useRef(FiatUnit.USD.endPointKey);
useEffect(() => { useEffect(() => {
let messagesListener = () => {}; let messagesListener = () => {};
if (isPaired && isInstalled && isReachable && walletsInitialized && messagesListenerActive.current === false) { if (isInstalled && isReachable && walletsInitialized && messagesListenerActive.current === false) {
messagesListener = watchEvents.addListener('message', handleMessages); messagesListener = watchEvents.addListener('message', handleMessages);
messagesListenerActive.current = true; messagesListenerActive.current = true;
} else { } else {
@ -37,14 +36,26 @@ function WatchConnectivity() {
messagesListenerActive.current = false; messagesListenerActive.current = false;
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [walletsInitialized, isPaired, isReachable, isInstalled]); }, [walletsInitialized, isReachable, isInstalled]);
useEffect(() => { useEffect(() => {
if (isPaired && isInstalled && isReachable && walletsInitialized) { console.warn(isInstalled, isReachable, walletsInitialized);
sendWalletsToWatch(); if (isInstalled && walletsInitialized) {
constructWalletsToSendToWatch().then(walletsToProcess => {
console.warn(walletsToProcess);
if (walletsToProcess) {
if (isReachable) {
transferUserInfo(walletsToProcess);
console.warn('sent info to watch transferUserInfo');
} else {
updateApplicationContext(walletsToProcess);
console.warn('sent info to watch context');
}
}
});
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [walletsInitialized, wallets, isPaired, isReachable, isInstalled]); }, [walletsInitialized, wallets, isReachable, isInstalled]);
useEffect(() => { useEffect(() => {
updateApplicationContext({ isWalletsInitialized: walletsInitialized, randomID: Math.floor(Math.random() * 11) }); updateApplicationContext({ isWalletsInitialized: walletsInitialized, randomID: Math.floor(Math.random() * 11) });
@ -78,8 +89,11 @@ function WatchConnectivity() {
reply({}); reply({});
}); });
} else if (message.message === 'sendApplicationContext') { } else if (message.message === 'sendApplicationContext') {
sendWalletsToWatch(); constructWalletsToSendToWatch().then(walletsToProcess => {
reply({}); if (walletsToProcess) {
updateApplicationContext(walletsToProcess);
}
});
} else if (message.message === 'fetchTransactions') { } else if (message.message === 'fetchTransactions') {
fetchWalletTransactions() fetchWalletTransactions()
.then(() => saveToDisk()) .then(() => saveToDisk())
@ -116,7 +130,7 @@ function WatchConnectivity() {
} }
}; };
const sendWalletsToWatch = async () => { const constructWalletsToSendToWatch = async () => {
if (!Array.isArray(wallets)) { if (!Array.isArray(wallets)) {
console.log('No Wallets set to sync with Watch app. Exiting...'); console.log('No Wallets set to sync with Watch app. Exiting...');
return; return;
@ -218,10 +232,10 @@ function WatchConnectivity() {
} }
walletsToProcess.push(walletInformation); walletsToProcess.push(walletInformation);
} }
updateApplicationContext({ wallets: walletsToProcess, randomID: Math.floor(Math.random() * 11) }); return { wallets: walletsToProcess, randomID: Math.floor(Math.random() * 11) };
}; };
return null; return <></>;
} }
export default WatchConnectivity; export default WatchConnectivity;

View file

@ -47,7 +47,7 @@
<key>WidgetsExtension.xcscheme_^#shared#^_</key> <key>WidgetsExtension.xcscheme_^#shared#^_</key>
<dict> <dict>
<key>orderHint</key> <key>orderHint</key>
<integer>147</integer> <integer>129</integer>
</dict> </dict>
</dict> </dict>
<key>SuppressBuildableAutocreation</key> <key>SuppressBuildableAutocreation</key>

View file

@ -10,7 +10,6 @@
#import <RNCPushNotificationIOS.h> #import <RNCPushNotificationIOS.h>
#import "EventEmitter.h" #import "EventEmitter.h"
#import <React/RCTRootView.h> #import <React/RCTRootView.h>
#import <WatchConnectivity/WatchConnectivity.h>
@interface AppDelegate() <UNUserNotificationCenterDelegate> @interface AppDelegate() <UNUserNotificationCenterDelegate>
@ -103,9 +102,6 @@
} }
- (void)applicationWillTerminate:(UIApplication *)application { - (void)applicationWillTerminate:(UIApplication *)application {
if ([[WCSession defaultSession] isReachable]) {
[WCSession.defaultSession updateApplicationContext:@{@"isWalletsInitialized": @NO} error:nil];
}
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.io.bluewallet.bluewallet"]; NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.io.bluewallet.bluewallet"];
[defaults removeObjectForKey:@"onUserActivityOpen"]; [defaults removeObjectForKey:@"onUserActivityOpen"];
} }

View file

@ -14,17 +14,29 @@ class InterfaceController: WKInterfaceController {
@IBOutlet weak var walletsTable: WKInterfaceTable! @IBOutlet weak var walletsTable: WKInterfaceTable!
@IBOutlet weak var noWalletsAvailableLabel: WKInterfaceLabel! @IBOutlet weak var noWalletsAvailableLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let contextUnwrapped = context as? [String: Any] {
WatchDataSource.shared.processData(data: contextUnwrapped)
}
if WCSession.isSupported() {
print("Activating watch session")
WCSession.default.delegate = self
WCSession.default.activate()
}
}
override func willActivate() { override func willActivate() {
// This method is called when watch view controller is about to be visible to user // This method is called when watch view controller is about to be visible to user
super.willActivate() super.willActivate()
if (WatchDataSource.shared.wallets.isEmpty) { if (WatchDataSource.shared.wallets.isEmpty) {
noWalletsAvailableLabel.setHidden(false) noWalletsAvailableLabel.setHidden(false)
} else { } else {
processWalletsTable() processWalletsTable()
} }
NotificationCenter.default.addObserver(self, selector: #selector(processWalletsTable), name: WatchDataSource.NotificationName.dataUpdated, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(processWalletsTable), name: WatchDataSource.NotificationName.dataUpdated, object: nil)
} }
@objc private func processWalletsTable() { @objc private func processWalletsTable() {
@ -50,3 +62,31 @@ class InterfaceController: WKInterfaceController {
} }
} }
extension InterfaceController: WCSessionDelegate {
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
WatchDataSource.shared.processData(data: applicationContext)
}
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
WatchDataSource.shared.processData(data: userInfo)
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
WatchDataSource.shared.companionWalletsInitialized = activationState == .activated
if activationState == .activated {
WatchDataSource.shared.processWalletsData(walletsInfo: WCSession.default.applicationContext)
}
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
WatchDataSource.shared.processData(data: message)
}
override func didDeactivate() {
WCSession.default.activate()
}
}

View file

@ -10,7 +10,7 @@
import Foundation import Foundation
import WatchConnectivity import WatchConnectivity
class WatchDataSource: NSObject, WCSessionDelegate { class WatchDataSource: NSObject {
struct NotificationName { struct NotificationName {
static let dataUpdated = Notification.Name(rawValue: "Notification.WalletDataSource.Updated") static let dataUpdated = Notification.Name(rawValue: "Notification.WalletDataSource.Updated")
} }
@ -30,11 +30,6 @@ class WatchDataSource: NSObject, WCSessionDelegate {
wallets = walletData wallets = walletData
WatchDataSource.postDataUpdatedNotification() WatchDataSource.postDataUpdatedNotification()
} }
if WCSession.isSupported() {
print("Activating watch session")
WCSession.default.delegate = self
WCSession.default.activate()
}
} }
func processWalletsData(walletsInfo: [String: Any]) { func processWalletsData(walletsInfo: [String: Any]) {
@ -100,14 +95,7 @@ class WatchDataSource: NSObject, WCSessionDelegate {
} }
} }
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
processData(data: applicationContext)
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
processData(data: applicationContext)
}
func processData(data: [String: Any]) { func processData(data: [String: Any]) {
if let preferredFiatCurrency = data["preferredFiatCurrency"] as? String, let preferredFiatCurrencyUnit = fiatUnit(currency: preferredFiatCurrency) { if let preferredFiatCurrency = data["preferredFiatCurrency"] as? String, let preferredFiatCurrencyUnit = fiatUnit(currency: preferredFiatCurrency) {
@ -122,19 +110,4 @@ class WatchDataSource: NSObject, WCSessionDelegate {
} }
} }
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
processData(data: userInfo)
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if activationState == .activated {
WCSession.default.sendMessage(["message" : "sendApplicationContext"], replyHandler: { (replyData) in
}) { (error) in
print(error)
}
} else {
WatchDataSource.shared.companionWalletsInitialized = false
}
}
} }

View file

@ -40,7 +40,7 @@ class ViewQRCodefaceController: WKInterfaceController {
DispatchQueue.main.async { DispatchQueue.main.async {
guard let cgImage = EFQRCode.generate( guard let cgImage = EFQRCode.generate(
content: passedContext) else { for: passedContext) else {
return return
} }
let image = UIImage(cgImage: cgImage) let image = UIImage(cgImage: cgImage)