Swift Compiler Error (Xcode): No such module 'shared_preferences_ios' - Flutter - xcode

Notes
Recently updated to Xcode Version 14.2 (14C18)
Flutter 3.7.0 • channel stable
Problem
When running my flutter app for ios, I get this error:
Xcode build done. 86.8s
Failed to build iOS app
Could not build the precompiled application for the device.
Swift Compiler Error (Xcode): No such module 'shared_preferences_ios'
/Users/tomasward/Desktop/fredi_new/ios/Runner/AppDelegate.swift:3:7
Which is derived from this piece of code in AppDelegate.swift:
import UIKit
import Flutter
import awesome_notifications
import shared_preferences_ios //error here
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
application.registerForRemoteNotifications()
SwiftAwesomeNotificationsPlugin.setPluginRegistrantCallback { registry in
SwiftAwesomeNotificationsPlugin.register(
with: registry.registrar(forPlugin: "io.flutter.plugins.awesomenotifications.AwesomeNotificationsPlugin")!)
FLTSharedPreferencesPlugin.register(
with: registry.registrar(forPlugin: "io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")!)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
This code is boilerplate for the awesome_notifications plugin setup for ios. See here
I Have tried a million solutions
Deleting ios build and running flutter create .
Running pod install a million times, deleting podfile, etc.
No solution seems to be consistent. I am looking for a general solution from people working on Flutter projects, not native ios projects.
Also it would be great if someone who worked with awesome_notifications could give me some insight

As you're probably already aware by now, shared_preferences_ios went away with shared_preferences version 2.0.16. So the fact you're seeing that means something didn't get updated correctly along the way.
What version of Flutter were you on previously?
FWIW my AppDelegate.swift looks quite different, and notably does not include imports for specific plugins:
import UIKit
import Flutter
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
On the other hand, I'm not using awesome_notifications. Is it possible the setup for it has changed since you first integrated, and the AppDelegate.swift modifications are no longer relevant? And, you're on the latest version of awesome_notifications?
Sorry I don't have an immediate and direct answer, but I hope this helps.

Kudos to the answer on this link:
This is issue created by shared_preferences v2.0.16. Long story short - package/module shared_preferences_ios was renamed to shared_preferences_foundation. Fastest way to work around this is to downgrade shared_preferences to 2.0.15.
shared_preferences: ^2.0.15 # Before
shared_preferences: 2.0.15 # After
You will then see this log when you run flutter pub get:
< shared_preferences 2.0.15 (was 2.0.17) (2.0.17 available)
+ shared_preferences_ios 2.1.1
+ shared_preferences_macos 2.0.5
Also, be careful with spelling mistakes as shared_prefrences_ios (wrong) is very similar to shared_preferences_ios (correct).

For Latest/Current Version do this below
replace shared_preferences_ios with shared_preferences_foundation
and FLTSharedPreferencesPlugin with SharedPreferencesPlugin
as these are the latest native bindings of flutter internal See PR.
AppDelegate.swift contents with new updated solution
import UIKit
import Flutter
import awesome_notifications
import shared_preferences_foundation //replace this here
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
application.registerForRemoteNotifications()
SwiftAwesomeNotificationsPlugin.setPluginRegistrantCallback { registry in
SwiftAwesomeNotificationsPlugin.register(
with: registry.registrar(forPlugin: "io.flutter.plugins.awesomenotifications.AwesomeNotificationsPlugin")!)
SharedPreferencesPlugin.register( // replace here
with: registry.registrar(forPlugin: "io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")!)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

Related

WKCrownDelegate doesn't seem to be working with Xcode 9 GM

I've tried the code below targeting both iOS 10.0/Watch OS 3.0 and iOS 11.0/Watch OS 4.0, and tested both in the simulator and my Watch OS 4 device. Nothing seems to trigger the crownDidRotate delegate method.
Simple interface with one label connected to the outlet. I know it's connected because I change the text in the awake method. Breaking in the delegate method never stops when I rotate the crown.
Any ideas?
import Foundation
import WatchKit
class InterfaceController: WKInterfaceController, WKCrownDelegate {
var value = 1
#IBOutlet var label: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
label.setText("Yeah?")
crownSequencer.delegate = self
crownSequencer.focus()
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
label.setText("Rotational: \(rotationalDelta)")
}
}
I had the same experience. As a hack, I added another call to crownSequencer.focus() in willActivate(), and I'm now seeing events. (xcode 9.0 gm, ios 11.0 gm, watchos 4.0 gm)
Adding crownSequencer.focus() in willActivate() did not help me in Xcode10.
You don't have to call crownSequencer.focus() neither in awake() or in willActivate() but in didAppear(). So you need to add the following lines:
override func didAppear() {
super.didAppear()
crownSequencer.focus()
}

My Parse Starter Project will not work. Swift 2.0 Xcode 7 beta 6

I have been trying to make an app with PARSE but I can't run it because I keep getting an error saying :
"Cannot invoke 'suscribeToChanelInBackground' with an argument list of type '(String, (Bool , NSError?)) -> ())''"
And it is pointing to the line of code:
PFPush.subscribeToChannelInBackground((succeeded: Bool, error: NSError?)){
Which is in the Push Notifications Section:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground((succeeded: Bool, error: NSError?)){
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.\n", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#\n", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
So I can't figure out what to do, I have been looking all over the web about it and I think it might be something to be to do with the new swift update Swift 2.0 (which I am using along with Xcode 7 beta) Is it my code , or parse's to do with the new swift? I have tried commenting it out because I don't need notifications in my app though apparently you need that section of code, and I might have to use the same code somewhere else which I think you do. Thank you in advance.
Ok, I have the answer, if you have this problem, the template you are given is for swift 1 and for Xcode 6, so I did find out that someone did edit the code to make it suitable for swift 2 , so if you have any problems with them template, just download it here:
Parse New Template
Note: This is not made by parse or by me and so far I have not had any problem with this so , sorry if this does not work for you, because I am using Xcode 7 beta 6 not 7

Failed to load optimized model at path error with Google Maps API using Xcode 7 / iOS9

I am trying to use the Google Places API autocomplete feature in my code.
import UIKit
import GoogleMaps
class ViewController: UIViewController, GMSMapViewDelegate {
var placesClient: GMSPlacesClient?
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient()
let filter = GMSAutocompleteFilter()
filter.type = GMSPlacesAutocompleteTypeFilter.City
placesClient?.autocompleteQuery("Pizza", bounds: nil, filter: filter, callback: { (results, error: NSError?) -> Void in
if let error = error {
print("Autocomplete error \(error)")
}
for result in results! {
if let result = result as? GMSAutocompletePrediction {
print("Result \(result.attributedFullText) with placeID \(result.placeID)")
}
}
})
}
}
When I run it I am getting this error: CoreData: Failed to load optimized model at path '/var/mobile/Containers/Bundle/Application/
Any ideas?
Add -ObjC to "Other Linker Flags"
(Build Settings -> Linking -> Other Linker Flags).
This solved it for me.
After I added this flag I received some errors regarding missing symbols (such as _CBAdvertisementDataManufacturerDataKey).
I added the Accelerate and CoreBluetooth frameworks in *Build Phases -> Link Binary With Libraries*.
This issue is fixed in the new update of Google maps
https://developers.google.com/maps/documentation/ios-sdk/releases?hl=en
Check this Link and update your local repositories

How to retrieve the OSX application that currently receives key events

I am following the cocoa documentation to determine the current front most application in OSX - aka the application which receives key events.
However, when I am executing the following swift the API always returns me the same value - XCode, but it never changes to chrome or any other application when I switch to them. I also tried to execute the compiled program but instead of constantly showing XCode it now shows whichever terminal app I am running.
What is the correct way of determining the application that receives the key events from OSX? Is my code in this regard broken?
import Cocoa
func getActiveApplication() -> String{
// Return the localized name of the currently active application
let ws = NSWorkspace.sharedWorkspace()
let frontApp = ws.frontmostApplication
return frontApp.localizedName
}
var frontMostApp : String
while true {
frontMostApp = getActiveApplication();
NSLog("front app: %#", frontMostApp)
sleep(1);
}
This thread is a bit old but was very helpful. I did some research based on Marco's post and uchuugaka's answer. The following is the result.
// swift 3.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared().notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSNotification.Name.NSWorkspaceDidActivateApplication,
object:nil)
}
dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()
I am a newbie in both Cocoa and Swift. I don't know if the above is efficient, but it works for me. I got help from How to create a minimal daemon process in a swift 2 command line tool? and Swift 3 NSNotificationCenter Keyboardwillshow/hide among numerous others.
Swift 4:
NSWorkspace.shared.notificationCenter.addObserver(self, // HERE, shared
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification, // HERE
object:nil)
Edit (Swift 4)
The compiler says the printMe function must be #objc. (I don't know the meaning, but it worked when I prepend #objc at the beginning of the line. Here is the full code for easy copy-paste.
// swift 4.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification,
object:nil)
}
#objc dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()
You you should do one thing differently, that is follow the NSWorkSpace notifications that tell you the applications resigned active or became active.
This is key especially as you are running in debug mode.
In debug mode Xcode is spawning your app as a child process.
In release mode it is basically doing the same as calling the open command in terminal.
In debug mode if you call this code too early and only once, you're not catching changes. Remember it's dynamic.

Swift - CLLocationManager not asking for user permission

I am with Xcode beta 2 and trying to get user location with OS X app, however it is not even asks user permission. here is what I did until now.
...
import CoreLocation
class AppDelegate: NSObject, NSApplicationDelegate, CLLocationManagerDelegate {
var locManager : CLLocationManager = CLLocationManager()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
//doSomething.
}
}
nothing happens. I looked other questions and try all suggested solutions from answers but did not work. Tried with Objective-C, all fine. Am I missing something here?
Location Service enabled on preferences of the computer. Also "NSLocationUsageDescription" is in info.plist. NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription for 10.10 and later, I am working on 10.9.
Information Property List Key Reference
There were no problem code wise, just noticed it is App Sandbox entitlement problem. Once I have checked Location under App Data it worked right away.

Resources