how to iOS mosquitto in background - ios

I have some problem for developing iOS app with libmosquitto
in my code
AppDelegate.swift
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MosquittoClientDelegate{
var window: UIWindow?
var client: MosquittoClient?
func didPublish(messageId: UInt) {
println( "didPublish \(messageId)" )
}
func didReceiveMessage(mosq_msg: MosquittoMessage!) {
println( "didReceiveMessage [ \(mosq_msg.mid)-\(mosq_msg.topic) ] \(mosq_msg.payload)" )
}
func didDisconnect() {
println( "didDisconnect" )
}
func didConnect(code: UInt) {
println( "didConnect \(code)" )
if code == UInt(MOSQ_ERR_SUCCESS.value){
client?.subscribe("sample", withQos: 1)
}
}
func didSubscribe(messageId: UInt, grantedQos qos: [AnyObject]!) {
println( "didSubscribe" )
}
func didUnsubscribe(messageId: UInt) {
println( "didUnsubscribe \(messageId)" )
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
client = MosquittoClient(clientId: "qq")
client?.host = "stick.coffee"
client?.port = 1883
client?.delegate = self
client?.connect()
return true
}
}
This working what i think except when app is exited.
I want receiveMessage even if app is exited.
and I founded there are some mode for background.
Audio and AirPlay
Location updates
Voice over IP
Newsstand downloads
External accessory communication
Uses Bluetooth LE accessories
Acts as Bluetooth LE accessory
Background fetch
Remote Notification
what is best mode for me?
Or is there some example for this stub?

Yep,
I found out there is no method for background running.
but voip can run in background if no need for uploading AppleStore.
so I implements with voip.

Related

How can plugins be used in another plugin's callback in the background?

I'm using this background_locator plugin and a geofencing plugin in my Flutter app. In the location callback function of the background_locator plugin I create geofences using the geofencing plugin. This works fine on Android. On iOS the background_locator plugin functions as it should, but calling geofencing methods in the callback has no effect. Calling the geofencing methods outside of the callback works without problems.
I found some resources addressing this: https://github.com/flutter/flutter/issues/21925 and https://github.com/flutter/engine/pull/7843 and changed the code in my AppDelegate.swift accordingly, but this issue still occurs. Any advice is appreciated!
Below is my AppDelegate.swift
import UIKit
import Flutter
import GoogleMaps
func registerPlugins(registry: FlutterPluginRegistry) -> () {
if (!registry.hasPlugin("BackgroundLocatorPlugin")) {
BackgroundLocatorPlugin.register(with: registry.registrar(forPlugin: "BackgroundLocatorPlugin"))
}
if (!registry.hasPlugin("GeofencingPlugin")) {
GeofencingPlugin.register(with: registry.registrar(forPlugin: "GeofencingPlugin"))
}
if (!registry.hasPlugin("FlutterLocalNotificationsPlugin")) {
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
}
if (!registry.hasPlugin("FLTSharedPreferencesPlugin")) {
FLTSharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "FLTSharedPreferencesPlugin"))
}
if (!registry.hasPlugin("FlutterSecureStoragePlugin")) {
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
}
}
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("$GOOGLE_MAPS_API_KEY")
GeneratedPluginRegistrant.register(with: self)
GeofencingPlugin.setPluginRegistrantCallback(registerPlugins)
BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins)
// iOS notification setup
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
// Prevent "old" notifications showing up after reinstallation
if(!UserDefaults.standard.bool(forKey: "Notification")) {
UIApplication.shared.cancelAllLocalNotifications()
UserDefaults.standard.set(true, forKey: "Notification")
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
I have face the issue with "FlutterGeofencing" that app will caught an exception "failed to set registerPlugins" and resolve the issue by set the callback
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
GeofencingPlugin.setPluginRegistrantCallback({_ in
})
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

pushRegistry(:didUpdate:for) not being called

I have looked at all questions about this but the answers to those have already been applied to my project but the pushRegistry() delegate method isn't getting invoked.
First here's the code:
import UIKit
import PushKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
print("App Launched");
self.registerVoIPPush();
return true
}
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
print("didUpdate");
print(pushCredentials);
print(type);
if type == PKPushType.voIP {
let tokenData = pushCredentials.token
let voipPushToken = String(data: tokenData, encoding: .utf8)
print(voipPushToken);
//send token to server
}
}
func registerVoIPPush() {
print("registerVoIPPush");
let voipPushResgistry = PKPushRegistry(queue: DispatchQueue.main)
voipPushResgistry.delegate = self
voipPushResgistry.desiredPushTypes = [PKPushType.voIP]
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
print(payload);
ATCallManager.shared.incommingCall(from: "jane#example.com", delay: 0)
}
}
I have also enabled following app capabilities: - Push Notifications -
Background Modes - Background Fetch - Remote Notifications - Voice
Over IP
I'm using Xcode11.3 & building using iOS13.2
On the provisioning portal Push Notifications have been enabled for the app id. (A VoIP Push cert has been generated & imported into keychain access as well but obviously can't use this to send the pushes yet).
Any help at all would be highly appreciated as I am trying to get this done since last 3 days.
Your PKPushRegistry object is deallocated as soon as registerVoIPPush() method is finished
Check if you set up appropriate background mode

Issues with Pubnub + Wink Hub and sensors

I'm trying to get my Wink Hub working with Pubnub subscriptions in my iOS app, but all I ever get is a PNUnexpectedDisconnectCategory status in the didReceiveStatus callback.
Here is the code:
class AppDelegate: UIResponder, UIApplicationDelegate, PNObjectEventListener {
var window: UIWindow?
var client: PubNub
override init() {
let configuration = PNConfiguration(publishKey: "", subscribeKey: "fake-key")
client = PubNub.clientWithConfiguration(configuration)
super.init()
client.addListener(self)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
client.subscribeToChannelGroups(
["sensor-channel0",
"sensor-channel1"],
withPresence: false)
return true
}
func client(client: PubNub, didReceiveMessage message: PNMessageResult) {
print("receivedMessage")
}
func client(client: PubNub, didReceiveStatus status: PNStatus) {
if status.category == .PNUnexpectedDisconnectCategory {
print("disconnected")
// This event happens when radio / connectivity is lost.
}
}
The subscribe and channel keys are taken straight from the device subscription data returned by the Wink API, so I am not sure what I am doing wrong. Any help would be appreciated!

iPhone freeze when using QuickActionItems

I have added 3D Touch on my app icon to show Quick Action menu. I think I should have it all set up correctly.
The problem is that when I am choosing one of the items in the Quick Action menu, the iPhone freezes for a few seconds before it opens up the application.
This is my AppDelegate.swift:
import UIKit
import Parse
#available(iOS 9.0, *)
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("xx",
clientKey: "xx")
let currentInstallation: PFInstallation = PFInstallation.currentInstallation()
currentInstallation.badge = 0
currentInstallation.saveEventually()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
let rootNavigationViewController = window!.rootViewController as? UINavigationController
let rootViewController = rootNavigationViewController?.viewControllers.first as UIViewController?
rootNavigationViewController?.popToRootViewControllerAnimated(false)
if shortcutItem.type == "JEGHARALDRI" {
rootViewController?.performSegueWithIdentifier("JEGHARALDRISEGUE", sender: nil)
}
if shortcutItem.type == "PLING" {
rootViewController?.performSegueWithIdentifier("PLINGSEGUE", sender: nil)
}
if shortcutItem.type == "FLASKETUTENPEKERPƅ" {
rootViewController?.performSegueWithIdentifier("FLASKETUTENPEKERPƅSEGUE", sender: nil)
}
if shortcutItem.type == "KORTETTALER" {
rootViewController?.performSegueWithIdentifier("KORTETTALERSEGUE", sender: nil)
}
}
}
I think your app delegate should more looks like something like this
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//MARK: - Properties
var window: UIWindow?
lazy var quickActionManager: QuickActionsManager = {
return QuickActionsManager()
}()
//MARK: - AppDelegate Methods
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
return self.setupQuickActions(launchOptions)
}
func application(application: UIApplication, performActionForShortcutItem
shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void)
{
completionHandler(self.quickActionManager.handleShortcut(shortcutItem))
}
//MARK: - Private Methods
private func setupQuickActions(launchOptions: [NSObject: AnyObject]?) -> Bool
{
guard let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey]
as? UIApplicationShortcutItem else { return false }
return self.quickActionManager.handleShortcut(shortcutItem)
}
}
And so then you get all the logic to handle a quick action in your quick action manager, which would looks something like this
//MARK: - Public Methods
func handleShortcut(shortcut: UIApplicationShortcutItem?) -> Bool
{
guard let shortcut = shortcut else { return false }
// Get the key of the shortcutItem
let key = self.shortKeyForType(shortcut.type)
// Check if that key is the key of a knowed viewController
guard let viewControllerKey = ViewControllerKeys(rawValue: key) else { return false }
// Try to show This View Controller
return self.showViewController(viewControllerKey)
}
Assuming you got an enum of viewController to display matching each quick actions.
I hope this answer your question, let me know if you got some more.

Integrating Chartboost to Swift

I have integrated all the chartboost the from https://answers.chartboost.com/hc/en-us/articles/201220095-iOS-Integration
but I'm keep getting these 18 errors in my chartboost.h file.
http://i.stack.imgur.com/s7Xek.png
I'm not sure if I made my AppDelegate.swift correct to integrate swift?
class AppDelegate: UIResponder, UIApplicationDelegate, ChartboostDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let kChartboostAppID = "559f1b52c909a64f054eb563";
let kChartboostAppSignature = "41ad09b1bd90bbf3b3712d9530f45daff3fbd04f";
Chartboost.startWithAppId(kChartboostAppID, appSignature: kChartboostAppSignature, delegate: self)
Chartboost.setShouldRequestInterstitialsInFirstSession(false)
return true
}
func showChartboostAds()
{
Chartboost.showInterstitial(CBLocationHomeScreen);
}
func didFailToLoadInterstitial(location :String!, withError error: CBLoadError)
{
}
func didDismissInterstitial(location :String! )
{
if(location == CBLocationHomeScreen)
{
Chartboost.cacheInterstitial(CBLocationMainMenu)
}
else if(location == CBLocationMainMenu)
{
Chartboost.cacheInterstitial(CBLocationGameOver)
}
else if(location == CBLocationGameOver)
{
Chartboost.cacheInterstitial(CBLocationLevelComplete)
}
else if(location == CBLocationLevelComplete)
{
Chartboost.cacheInterstitial(CBLocationHomeScreen)
}
}
please help i have been stuck here for a while now please can you help?
I had the same the problem. I brought the entire Chartboost folder into my project instead of just the framework. Go into the folder and delete ChartboostExample. There's an example Xcode project in there that seems to causing weird things to happen.

Resources