Ionic 3 background mode return as false - ionic-framework

I use Ionic 3 and I want my app to work in the background as well, and now I try to use background mode of Ionic 3 in app.component, using this.backgroundMode.enable() and then use method isEnable() but when I use isEnable() it return as false. What did I do wrong, why is it return as false? Please help me
import { BackgroundMode } from '#ionic-native/background-mode';
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private backgroundMode: BackgroundMode) {
platform.ready().then(() => {
this.backgroundMode.enable()
var bgmStatus = this.backgroundMode.isEnabled();
console.log(bgmStatus);
statusBar.styleDefault();
splashScreen.hide();
});
}
}
import { BackgroundMode } from '#ionic-native/background-mode';
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private backgroundMode: BackgroundMode) {
platform.ready().then(() => {
this.backgroundMode.enable()
var bgmStatus = this.backgroundMode.isEnabled();
console.log(bgmStatus);
statusBar.styleDefault();
splashScreen.hide();
});
}
}

Related

RealmSwift not syncing with MongoDB what is missed in this code?

I'm using realm backend for my swiftui project and it's never been synced so if I add object it's appear locally but not appears in mongodb app service,
so if I try to add object it's appears in local but it doesn't appear in app service and if I fetch the data it fetches the local data only and the items in app service collection doesn't appear
can someone help me what is missed in my code and here's my code
import SwiftUI
import RealmSwift
let app: RealmSwift.App? = RealmSwift.App(id: "swift-app-azpkw")
#main
struct RealAgenApp: SwiftUI.App {
var body: some Scene {
WindowGroup {
if let app = app {
AppContainer(app: app)
} else {
AuthView()
}
}
}
}
import SwiftUI
import RealmSwift
struct AppContainer: View {
#ObservedObject var app: RealmSwift.App
var body: some View {
if let user = app.currentUser {
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
if subs.first(named: "Property") != nil {
return
} else {
subs.append(QuerySubscription<Property>(name: "Property") {
$0.ownerId == user.id
})
}
})
AppView()
.environment(\.realmConfiguration, config)
} else {
AuthView()
}
}
}
import SwiftUI
import RealmSwift
struct AppView: View {
#AutoOpen(appId: "APP_ID", timeout: 4000) var autoOpen
var body: some View {
let _ = app?.currentUser // id: 637ceaf802e0885f39a06d71
switch autoOpen {
case .connecting:
MessageView(message: "Connecting")
case .waitingForUser:
MessageView(message: "Waiting for user to log in...")
case .open(let realm):
HomeView()
.environment(\.realm, realm)
case .progress(let progress):
LoadingView(progress: progress)
case .error(let error):
MessageView(message: error.localizedDescription)
.foregroundColor(.red)
}
}
}
import SwiftUI
import Realm
import RealmSwift
struct HomeView: View {
#ObservedResults(Property.self) var properties
var body: some View {
ForEach(properties) { category in
Text("Category")
}
}
}
Greetings
after a long search and reconfiguration of the app service I've just realized that the issue was initialSubscriptions of flexibleSyncCOnfiguration not calling and also I reconfigure the schema rules in App service UI
here's my final config initialize
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subscriptions in
if let _ = subscriptions.first(named: "all-properties") {
return
} else {
subscriptions.append(QuerySubscription<Property>(name: "all-properties"))
}
}, rerunOnOpen: true)

Functions of WKExtensionDelegate are not called for watchOS

This is my WatchDelegate.swift:
import WatchKit
class WatchDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
print("FINISHED LAUNCHING>>>>>>>>>>>") //not called
}
}
My info.plist:
My app is launching on my watch, but above delegate method is not called. Why?
In my case I didn't add anything to info.plist, I just added some magic swift sprinkles:
import SwiftUI
#main
struct WatchApp: App {
// 👇👇👇
#WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate: ExtensionDelegate
// 👆👆👆
var body: some Scene {
WindowGroup {
// etc
I then see logging from
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// stuff logged here shows in console
}
}

get ApplicationContext on react-native

I have a watchKit app connected with a react-native iOS app with react-native-watch-connectivity.
I want to use the applicationContext to communicate between the devices.
From react-native, I use watch.updateApplicationContext({ dataFromRN: "data" }) to define it and I can get it in iWatch side.
But when I use updateApplicationContext(["data":"data"]) in iWatch side, an updated context event is catch by react-native but the data is not updated.
// iWatch
try session?.updateApplicationContext(["dataFromWatch":"data"])
print(session?.applicationContext ?? "")
["dataFromWatch": "data"]
but in react-native, I have the following output for this event:
// react-native iOS
receiveApplicationContext(err, applicationContext) {
console.log("receiveApplicationContext()", applicationContext)
receiveApplicationContext() {dataFromRN: "data"}
dataFromRN is a previous applicationContext defined from react-native side.
Event if react-native catch an event, the applicationContext is not updated.
(react-native-watch-connectivity has react version defined to 15.4.2 but I'm using react 16.2.0. Is something can be breaking changed between this versions ?)
I guess I have to update something in react-native-watch-connectivity, but I would like to know where.
If you have any element to fix this issue...
Thx
iOS side (with react-native)
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
ScrollView,
AsyncStorage,
TouchableHighlight
} from "react-native";
import * as watch from "react-native-watch-connectivity";
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = { match: [] };
this.receiveUserInfo = this.receiveUserInfo.bind(this);
this.subscribeToApplicationContext = this.subscribeToApplicationContext.bind(this);
this.subscribeToWatchEvents = this.subscribeToWatchEvents.bind(this);
}
receiveUserInfo(err, userInfo) {
if (!err) {
if (userInfo.currentMatch !== undefined) {
console.log("receiveUserInfo()", userInfo);
}
}
}
receiveApplicationContext(err, applicationContext) {
if (!err) {
console.log("receiveApplicationContext()", applicationContext);
watch.getApplicationContext().then(context => {
console.log("getApplicationContext()", context);
});
}
}
subscribeToWatchEvents() {
this.subscriptions = [
watch.subscribeToUserInfo(this.receiveUserInfo),
watch.subscribeToApplicationContext(this.receiveApplicationContext)
];
}
componentDidMount() {
this.subscribeToWatchEvents();
}
componentWillUnmount() {}
render() {
return (
<View/>
);
}
}
iWatch side (swift)
import WatchKit
import Foundation
import WatchConnectivity
class MainController: WKInterfaceController, WCSessionDelegate {
var session: WCSession?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if WCSession.isSupported() {
self.session = WCSession.default
self.session?.delegate = self
self.session?.activate()
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("activationDidCompleteWith", activationState)
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
print("didReceiveApplicationContext", applicationContext)
}
func sendUserInfo() {
session?.transferUserInfo(["data":"data"])
do {
try session?.updateApplicationContext(["data":"data"])
} catch {
print("updateApplicationContext error")
}
print(session?.applicationContext ?? "")
}
#IBAction func point() {
sendUserInfo()
}
}
There doesn't seem to be any issue in your MainController InterfaceController but if you send the same message via updateApplicationContext:, it's ignored on the other counterpart app by default.
Basically, do not to send the same applicationContext.
Check this, for test purpose, we just add a random number to the applicationContext payload so it is different for successive calls.
func sendUserInfo() {
do {
try session?.updateApplicationContext(["from" : "watch \(arc4random()"])
}
catch {
print(error)
}
}

ionic 2 - Property 'dismiss' does not exist on type 'ActionSheetController'

I am following the doc trying to create Actionsheet. Not sure why getting the error message Property 'dismiss' does not exist on type 'ActionSheetController' on the dismiss() and Cannot find name someAsyncOperation for the someAsyncOperation().
Did I miss anything?
import { ActionSheetController } from 'ionic-angular';
import { IonicPage, NavController, NavParams, ModalController, ViewController } from 'ionic-angular';
constructor(
public viewCtrl: ViewController,
public navCtrl: NavController,
public actionSheetCtrl: ActionSheetController,
public modalCtrl: ModalController,
public navParams: NavParams,
) {}
openActSheet(){
let actionSheet = this.actionSheetCtrl.create({
title:"Type",
buttons:[
{
text: 'Hour',
handler: () => {
let navTransition = this.actionSheetCtrl.dismiss();
someAsyncOperation().then(() => {
console.log("text");
})
navTransition.then(() => {
this.navCtrl.pop();
});
}
},
{
text: 'Day',
handler: function(){
console.log("Day Clicked");
}
},
{
text: 'Week',
handler: function(){
console.log("Week Clicked");
}
},
{
text: 'Month',
handler: function(){
console.log("Month Clicked");
}
}
]
});
actionSheet.present();
}
ActionSheetController does not have dismiss() function. It is available in actionsheet Object.
Try:
openActSheet(){
let actionSheet = this.actionSheetCtrl.create({
title:"Type",
buttons:[
{
text: 'Hour',
handler: () => {
let navTransition = actionSheet.dismiss(); //here
//....

Implementing PHPhotoLibraryChangeObserver protocol in swift

I'm trying to set my AssetService as changeObserver, but I get the folowing error:
Error:(8, 14) type 'AssetService' does not conform to protocol 'PHPhotoLibraryChangeObserver'
While photoLibraryDidChange is the only required method. Here's my code:
import UIKit
import Photos
public class AssetService : PHPhotoLibraryChangeObserver {
public init() {
// here I do some other stuff
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
public func photoLibraryDidChange(changeInstance: PHChange) {
dispatch_async(dispatch_get_main_queue(), {
})
}
}
I think you need to extend from NSObject in order to use it in the PhotoFramework
Therefore you need also to override the init and add super.init()
import UIKit
import Photos
public class AssetService : NSObject, PHPhotoLibraryChangeObserver {
public override init() {
super.init()
// here I do some other stuff
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
public func photoLibraryDidChange(changeInstance: PHChange) {
dispatch_async(dispatch_get_main_queue(), {
})
}
}
Hope this will solve it
In Swift 3.0 the register actually looks like this now:
func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.async {
}
}
public override init() {
super.init()
PHPhotoLibrary.shared().register(self)
}
Everything else is the same in Bart Schoon's answer