Adding CarPlay to a SwiftUI lifecycle app - ios

What is the recommended way to integrate CarPlay into an app which uses a SwiftUI lifecycle ?
#main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
How do I use the CPTemplateApplicationSceneDelegate here ?

If you don't have a custom app delegate and/or scene delegate (you might need it eventually for stuff like push notifications) it should be enough to let your app know via the info.plist. You need a scene delegate for the CarPlay scene and add the following to your info.plist:
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<true/>
<key>UISceneConfigurations</key>
<dict>
<key>CPTemplateApplicationSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneClassName</key>
<string>CPTemplateApplicationScene</string>
<key>UISceneConfigurationName</key>
<string>TemplateSceneConfiguration</string>
<key>UISceneDelegateClassName</key>
<string>AppFeature.CarPlaySceneDelegate</string>
</dict>
</array>
</dict>
</dict>
The value for UISceneConfigurationName is handed to you in the scene delegate's scene(_:willConnectTo:options:) session.configuration.name.
The value for UISceneDelegateClassName has to match your CarPlay scene delegate's Type name. Note that if you encapsulate your CarPlay code in a package/framework you need to prefix the delegate's name with the module name (in this case AppFeature). If the delegate is in your app target just use CarPlaySceneDelegate.
An excerpt of the scene delegate might look like this:
class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
let templateManager = TemplateManager() // see Apple's sample code
func templateApplicationScene(_: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) {
templateManager.connect(interfaceController)
}
func templateApplicationScene(_: CPTemplateApplicationScene, didDisconnectInterfaceController _: CPInterfaceController) {
templateManager.disconnect()
}
}

Related

Flutter / Swift Compiler Error (Xcode): Cannot find 'ExternalLinkAccount' in scope

Since 12th october 2022, reader's app with external account management/purchase must have to declare a new entitlement.
External Link Account
Enable qualifying apps to link to an external website for account creation or management.
https://developer.apple.com/documentation/storekit/external_link_account
I can't build because :
Swift Compiler Error (Xcode): Cannot find 'ExternalLinkAccount' in scope
Configure the SKExternalLinkAccount property list key.
<plist>
<dict>
<key>SKExternalLinkAccount</key>
<dict>
<key>*</key>
<string>https://example.com</string>
<key>jp</key>
<string>https://example.com/jp</string>
</dict>
</dict>
</plist>
Runner plist
<key>com.apple.developer.storekit.external-link.account</key>
<true/>
Runner entitlement
<plist>
<dict>
<key>com.apple.developer.storekit.external-link.account</key>
<true/>
</dict>
</plist>
ios build (with flutter run) :
Swift Compiler Error (Xcode): Cannot find 'ExternalLinkAccount' in scope
My code in a custom swift file (called with a platform specific call)
import SwiftUI
struct ExternalLinkAccountModal: View {
var body: some View {
Text("Hello, world!")
.padding()
.onAppear {
Task {
await executeTask()
}
}
}
}
struct ExternalLinkAccountModal_Previews: PreviewProvider {
static var previews: some View {
ExternalLinkAccountModal(onConfirm: nil, onCancel: nil)
.previewDevice("iPhone 13")
.previewInterfaceOrientation(.portrait)
}
}
func executeTask() async {
let basicTask = Task {
if await ExternalLinkAccount.canOpen {
do {
try await ExternalLinkAccount.open()
} catch {
print("ExternalLinkAccount.open() error \(error)")
}
}
}
}
Provisioning profile
My provisioning profile is well configured and accepted by Apple Developper :
Associated Domains, External Link Account, In-App Purchase, Push Notifications
Can you help to fix this ?
I'm using osx Ventura and ios16 platform for developping.

Unable to call Device Activity in Screen Time Api From Parent Device

Using shared authorization I am able to authorize the child's device and able to see all the installed apps on the child's mobile on the parent device. But when I am trying to call DeviceActivity nothing happens. This is how I am calling DeviceActivity
class MyDeviceActivityMonitor: DeviceActivityMonitor{
override func intervalDidStart(for activity: DeviceActivityName) {
super.intervalDidStart(for: activity)
}
override func intervalDidEnd(for activity: DeviceActivityName) {
super.intervalDidEnd(for: activity)
}
override func eventDidReachThreshold(_ event:DeviceActivityEvent.Name,activity:DeviceActivityName){
super.eventDidReachThreshold(event, activity: activity)
}
}
info.plist
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.deviceactivity.monitor-extension</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).DeviceActivityMonitorExtension</string>
</dict>
I am stuck in this issue too. Have you tried changing the NSExtensionPrincipalClass to the below?
<string>$(PRODUCT_MODULE_NAME).MyDeviceActivityMonitor </string>

iOS/macOS - best way to draw an image/icon ready to be tinted by system

What is the best way to create a set of icons influenced by the operating system to display a colored / accent version?
As with the;
 
selected version
accent version
I have about 10 black versions, but would like to have them adjusted with either selected or system chosen accent color. What should I have to do with my icons to let them coloured by the OS
Any road map?
This code shows you how to add set an alternative icon based on iOS theme, and your settings bundle. I've also added accent1Icon and accent2Icon as examples.
In your Settings.bundle, you need to add a Multi Value - App item to Preference Items (Apple requires that users can change the theme, even if you automatically set it based on their iOS settings):
<dict>
<key>Type</key>
<string>PSMultiValueSpecifier</string>
<key>Values</key>
<array>
<string>0</string>
<string>1</string>
<string>2</string>
<string>3</string>
<string>4</string>
</array>
<key>Title</key>
<string>App Icon Theme</string>
<key>Key</key>
<string>app_icon_theme</string>
<key>DefaultValue</key>
<string>0</string>
<key>Titles</key>
<array>
<string>Use iOS Theme</string>
<string>Dark Theme</string>
<string>Light Theme</string>
<string>Accent1 Theme</string>
<string>Accent2 Theme</string>
</array>
</dict>
Create a class that minimally has your app_icon_theme setting:
class SettingsBundleHelper {
struct SettingsBundleKeys {
static let AppIconThemeKey = "app_icon_theme"
}
}
Add this to your info.plist:
<dict>
<key>CFBundleAlternateIcons</key>
<dict>
<key>darkIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>name-of-dark-icon</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
<key>accent1Icon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>name-of-accent1-icon</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
<key>accent2Icon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>name-of-accent2-icon</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</dict>
Create a folder in your project called Alternate Icons and save a name-of-dark-icon#2x.png and name-of-dark-icon#3x.png in it.
YourProject
|
+-- Alternate Icons (folder)
|
+-- name-of-dark-icon#2x.png
+-- name-of-dark-icon#3x.png
+-- name-of-accent1-icon#2x.png
+-- name-of-accent1-icon#3x.png
+-- name-of-accent2-icon#2x.png
+-- name-of-accent2-icon#3x.png
You could run the changeIcon code in your AppDelegate applicationDidBecomeActive (or elsewhere). If you choose to run it there, you'll need to add this to your AppDelegate file:
enum AppIconTheme: String {
case UseiOSTheme = "0"
case DarkTheme = "1"
case LightTheme = "2"
case Accent1Theme = "3"
case Accent2Theme = "4"
}
func applicationDidBecomeActive(_ application: UIApplication) {
// update icon if dark mode
if #available(iOS 12.0, *) {
var theme = AppIconTheme.UseiOSTheme
if let iconTheme = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.AppIconThemeKey) {
if let themeSettings = AppIconTheme(rawValue: iconTheme) {
theme = themeSettings
}
}
print(theme as Any)
switch (theme) {
case .UseiOSTheme:
if UIApplication.shared.windows[0].rootViewController?.traitCollection.userInterfaceStyle == .dark {
self.changeIcon(to: "darkIcon")
} else {
self.changeIcon(to: nil)
}
case .LightTheme:
self.changeIcon(to: nil)
case .DarkTheme:
self.changeIcon(to: "darkIcon")
case .Accent1Theme:
self.changeIcon(to: "accent1Icon")
case .Accent2Theme:
self.changeIcon(to: "accent2Icon")
}
} else {
// Fallback on earlier versions
var theme = AppIconTheme.UseiOSTheme
if let iconTheme = UserDefaults.standard.string(forKey: SettingsBundleHelper.SettingsBundleKeys.AppIconThemeKey) {
theme = AppIconTheme(rawValue: iconTheme)!
}
print(theme as Any)
switch (theme) {
case .UseiOSTheme:
self.changeIcon(to: nil)
case .LightTheme:
self.changeIcon(to: nil)
case .DarkTheme:
self.changeIcon(to: "darkIcon")
case .Accent1Theme:
self.changeIcon(to: "accent1Icon")
case .Accent2Theme:
self.changeIcon(to: "accent2Icon")
}
}
}
func changeIcon(to name: String?) {
//Check if the app supports alternating icons
guard UIApplication.shared.supportsAlternateIcons else {
return;
}
if UIApplication.shared.alternateIconName != name {
//Change the icon to a specific image with given name
// if name is nil, the app icon will be the default app icon
UIApplication.shared.setAlternateIconName(name) { (error) in
//After app icon changed, print our error or success message
if let error = error {
print("App icon failed to due to \(error.localizedDescription)")
} else {
print("App icon changed successfully.")
}
}
}
}
Here is the documentation from Apple on setAlternativeIcon:
https://developer.apple.com/documentation/uikit/uiapplication/2806818-setalternateiconname

Can't get an item's attributes from a DynamoDB table

I have an iOS app written in Swift. In this app I'm trying to load an item from a DynamoDB table, but for some reason, I couldn't load any item, even though all the details were correct.
I have installed the AWS SDK using CocoaPods, after I followed all the instructions in order to correctly install it. I have installed the following libraries: AWSCognito, AWSCognitoIdentityProvider, AWSDynamoDB, AWSS3, AWSSNS.
After that, I have added my AWS credentials in the Info.plist file:
<key>AWS</key>
<dict>
<key>DynamoDBObjectMapper</key>
<dict>
<key>Default</key>
<dict>
<key>Region</key>
<string>USEast1</string>
</dict>
</dict>
<key>DynamoDB</key>
<dict>
<key>Default</key>
<dict>
<key>Region</key>
<string>USEast1</string>
</dict>
</dict>
<key>CredentialsProvider</key>
<dict>
<key>CognitoIdentity</key>
<dict>
<key>Default</key>
<dict>
<key>Region</key>
<string>USEast1</string>
<key>PoolId</key>
<string>myPoolId</string>
</dict>
</dict>
</dict>
</dict>
I've created a mapper file called Contact.swift:
import UIKit
import AWSDynamoDB
class Contact: AWSDynamoDBObjectModel, AWSDynamoDBModeling {
var id: String?
var name: String?
class func dynamoDBTableName() -> String {
return "Contacts"
}
class func hashKeyAttribute() -> String {
return "id"
}
}
Then, I've added the following code in ViewController.swift file, inside the viewDidLoad method. The code should get an item from a table, save its attributes, and set its name attribute to be the title of the screen:
import UIKit
import AWSDynamoDB
class ViewController: UIViewController {
//MARK: Properties
struct GlobalVars {
static let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
static let id: String = "id"
static var name: String?
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
GlobalVars.dynamoDBObjectMapper.load(Contact.self, hashKey: GlobalVars.id, rangeKey: nil).continueWith(block: {(task: AWSTask<AnyObject>!) -> Any? in
if let error = task.error as NSError? {
print("The request failed. Error: \(error)")
} else if let taskResult = task.result as? Contact {
// Save the information
GlobalVars.name = taskResult.name
// Set title to the name
self.navigationItem.title = GlobalVars.name!
}
return nil
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The problem is that the app crashes when I'm trying to assign the GlobalVars.name variable to the navigation bar title. It crashes with the following message: Fatal error: Unexpectedly found nil while unwrapping an Optional value.
I've tried to print taskResult.name instead, but it just printed nil.
But it didn't print anything to the console. I've added the following code to the Info.plist file, but that didn't work also:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>amazonaws.com</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>amazonaws.com.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
When I'm checking in the variables area at the bottom of the editor, I can see that all of the item's attributes are nil.
After a deep search, I've noticed something very weird. When I changed the name of the table to a table which doesn't exist, I have received the following message in the console:
The request failed. Error: Error Domain=com.amazonaws.AWSDynamoDBErrorDomain Code=7 "(null)" UserInfo={__type=com.amazonaws.dynamodb.v20120810#ResourceNotFoundException, message=Requested resource not found}
When I'm running it with a correct table name, but with a wrong hash key which refers to an item which doesn't exist in the table, I don't get anything. It doesn't crashes or prints a message to the console. It just keeps running like I'm don't asking for anything from the DynamoDB table.
What can I do about it? I've already searched all over the internet but I couldn't find anything about it yet... Could you please help me solving that?
So apparently, due to a change in Swift 4 behavior change of inferencing #objc, I was supposed to add #objcMembers before the class declaration in the Contact.swift file

Facebook login with Parse in iOS9 and Swift2

I am trying to login with Facebook with Parse in iOS9 but the application keep opening Safari instead of Facebook app in real device. and even in Safari when I try to use the keyboard to enter the email and password of Facebook account the page reload so it's impossible to login and give the permission to the app. The user should open safari and login first in Facebook then open my app and then give permission. I think it's not the best user experience since the user have already a Facebook app.
I have followed all the steps I will list them here:
Add Fraleworks
Link Binaries
Updaded info.plist
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb907580375984874</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>FacebookAppID</key>
<string>907580375984874</string>
<key>FacebookDisplayName</key>
<string>Appname</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
<string>fbauth</string>
<string>fbauth2</string>
<string>fb-messenger-api20140430</string>
</array>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>akamaihd.net</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>facebook.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>fbcdn.net</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
App Delegate
import UIKit
import Parse
import FBSDKCoreKit
import ParseFacebookUtilsV4
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("appID", clientKey: "MyKey")
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application,openURL: url,sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
}
Login code:
#IBAction func loginButtonClicked(sender: AnyObject) {
if let _ = FBSDKAccessToken.currentAccessToken() {
print("connected already")
} else {
PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile", "email", "user_friends", "user_birthday" , "user_education_history","user_photos"]) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
print("User signed up and logged in through Facebook!")
} else {
print("User logged in through Facebook!")
}
} else {
print("Uh oh. The user cancelled the Facebook login.")
}
}
}
}
Using a webview to log users in is now the default behaviour of the Facebook SDK for iOS 9 and according to Facebook team, this approach gives a better user experience as it avoids the additional dialogues being shown between app transitions.
In apps that use the newest SDK (v4.6 and v3.24), we will surface a
flow using Safari View Controller (SVC) instead of fast-app-switching
(FAS) because of additional dialog interstitials that add extra steps
to the login process in FAS on iOS 9. Additionally, data that we've
seen from more than 250 apps indicate that this is the best experience
for people in the long run
Read more on Facebook

Resources