I'm trying to integrate Shopify SDK on a SwiftUI project and I'm having some troubles with the authentication flow.
The code provided on the documentation is pretty straight forward:
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
spotifyConnection.sessionManager.application(application, open: url, options: options)
return true
}
with SwiftUI though this delegate method is never called so I'm trying to use openUrl
var body: some Scene {
WindowGroup {
MenuView()
.onOpenURL { (url) in
spotifyConnection.sessionManager.application(??, open: url, options: ??)
}
}
}
Question is how do I access the parameters application and options from here?
I am also having the same issue, for Spotify SDK particularly, I tried passing in UIApplication.shared and an empty options dictionary, which seems to work. I also tried examining the options dictionary when I use a UIKit AppDelegate lifecycle. It shows it's returning openInPlace to be false in the options dictionary in the Spotify url callback.
You need an UIApplicationDelegateAdaptor
#main
struct MyApp: App {
#UIApplicationDelegateAdaptor private var appDelegate: MyAppDelegate
var body: some Scene { ... }
}
class MyAppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
spotifyConnection.sessionManager.application(application, open: url, options: options)
return true
}
}
Related
I'm following the latest tutorial from Stream Chat, which looks great.
Looks like I followed it to the letter except for I replaced the apiKey with one created for me in the dashboard. This was provided when I registered my free trial.
Unfortunately, I'm unable to connect.
Here's my code
SwiftUIChatDemo
import SwiftUI
// 1 Add imports
import StreamChat
import StreamChatSwiftUI
#main
struct SwiftUIChatDemoApp: App {
// 2 Add Adapter
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ChatChannelListView()
}
}
}
App Delegate
import StreamChat
import StreamChatSwiftUI
import UIKit
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
// Add context provider
var streamChat: StreamChat?
var chatClient: ChatClient = {
// Low-level client variable with a hard-coded apikey
var config = ChatClientConfig(apiKey: .init("[key I created in dashboard]"))
// Set to use the chat in offline mode
config.isLocalStorageEnabled = true
// Pass the low-level client variable as a parameter of the ChatClient
let client = ChatClient(config: config)
return client
}()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Initialize the stream chat client
streamChat = StreamChat(chatClient: chatClient)
connectUser()
return true
}
// The `connectUser` function we need to add.
private func connectUser() {
// This is a hardcoded token valid on Stream's tutorial environment.
let token = try! Token(rawValue: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoibHVrZV9za3l3YWxrZXIifQ.kFSLHRB5X62t0Zlc7nwczWUfsQMwfkpylC6jCUZ6Mc0")
// Call `connectUser` on our SDK to get started.
chatClient.connectUser(
userInfo: .init(id: "luke_skywalker",
name: "Luke Skywalker",
imageURL: URL(string: "https://vignette.wikia.nocookie.net/starwars/images/2/20/LukeTLJ.jpg")!),
token: token
) { error in
if let error = error {
// Some very basic error handling only logging the error.
log.error("connecting the user failed \(error)")
return
}
}
}
}
SwiftUIChatDemo.app
import SwiftUI
// 1 Add imports
import StreamChat
import StreamChatSwiftUI
#main
struct SwiftUIChatDemoApp: App {
// 2 Add Adapter
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ChatChannelListView()
}
}
}
When you change the apiKey, you will need to generate new tokens with the secret that's provided to you in the dashboard. For development, you can generate tokens with the tool here: https://getstream.io/chat/docs/ios-swift/tokens_and_authentication/?language=swift#manually-generating-tokens. The user id also needs to match to your user. Note that for production usage, you should generate this tokens on a backend.
In case of additional questions, you can also reach our support channel: https://getstream.io/contact/support/
UPDATE
So, I got it working with the apiKey and token values from the tutorial. Well done. How I do this with my own values probably requires my own users.
In the iOS 13 world, I had code like this:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShare.Metadata) {
// do stuff with the metadata, eventually call CKAcceptSharesOperation
}
}
I am migrating my app to the new SwiftUI app lifecycle, and can’t figure out where to put this method. It used to live in AppDelegate pre-iOS13, and I tried going back to that, but the AppDelegate version never gets called.
There doesn’t seem to be a SceneDelegateAdaptor akin to UIApplicationDelegateAdaptor available, which would provide a bridge to the old code.
So, I’m lost. How do I accept CloudKit shares with SwiftUI app lifecycle? 🙈
You can still use AppDelegate with SwiftUI's new life-cycle until Apple releases APIs to handle this natively in SwiftUI’s App Life-cycle.
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
#main
struct MyApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Read this for more
I am trying to open specific view controller on widgets click , but can not able to open it , i am able to open app using url schema but i want to open specific view controller how can i do this, here is code for open app using url schema :
#IBAction func open_app(_ sender: Any)
{ extensionContext?.open(URL(string: "open://")! ,
completionHandler: nil)
}
on button click i am opeing app sucessfully using url schema. but now i want to open specific view controller on that click how can i do this?
According to your requirement, I have created a sample to get this working correctly.
1. First of all in TodayViewController interface, create 3 different UIButtons and give their tag values to uniquely identify them.
Here I have given tags as: 1, 2, 3 to First, Second and Third UIButton.
2. Next you need to write the code to open your Containing App from Today Extension. In TodayViewController create an #IBAction for and connect it to all three UIButtons.
#IBAction func openAppController(_ sender: UIButton)
{
if let url = URL(string: "open://\(sender.tag)")
{
self.extensionContext?.open(url, completionHandler: nil)
}
}
In the above code, tag will be added to the url scheme to identify which UIViewController needs to be opened on UIButton press. So the url will look something like: open://1
3. In the Containing App's URL Types need to make an entry for URL Scheme, i.e
As evident from the above screenshot, there is no need to make entry for each url that you want to open from your extensions. URLs having same url scheme have only a single entry.
4. When the containing app is opened from extension, you can get the handle in AppDelegate’s application(_ : url: sourceApplication: annotation: ) method. Here, you can handle which controller to open i.e.
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
if url.scheme == "open"
{
switch url.host
{
case "1":
//Open First View Controller
case "2":
//Open Second View Controller
case "3":
//Open Third View Controller
default:
break
}
}
return true
}
url.scheme identifies the scheme of URL i.e. open and url.host identifies the host component in the URL which is currently set to the UIButton's tag value which you can use to uniquely identify which UIButton is pressed and what to de next accordingly.
For more on Today Extensions, you can refer to: https://hackernoon.com/app-extensions-and-today-extensions-widget-in-ios-10-e2d9fd9957a8
Let me know if you still face any issues regarding this.
add a new scheme for your App
enter image description here
as Shown above image...
then, write a code below on IBAction of your Today Extension
#IBAction func btnFirstWidgetAction() {
let url: URL? = URL(string: "schemename://secondViewController")!
if let appurl = url { self.extensionContext!.open(appurl, completionHandler: nil) }
}
#IBAction func btnSecondWidgetAction() {
let url: URL? = URL(string: "schemename://secondViewController")!
if let appurl = url { self.extensionContext!.open(appurl, completionHandler: nil) }
}
#IBAction func btnThirdWidgetAction() {
let url: URL? = URL(string: "schemename://thirdViewController")!
if let appurl = url { self.extensionContext!.open(appurl, completionHandler: nil) }
}
than, add method application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) in AppDelegate file and write code to redirect in specific ViewController in this method.
//call when tap on Extension and get url that is set into a ToadyExtension swift file...
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let urlPath : String = url.absoluteString
print(urlPath)
if self.isContainString(urlPath, subString: "firstViewController") {
//here go to firstViewController view controller
}
else if self.isContainString(urlPath, subString: "firstViewController") {
//here go to secondViewController view controller
}
else {
//here go to thirdViewController view controller
}
return true
}
this method used for check your string is contains as sub string that are given in widget button action. if contain than true otherwise false
func isContainString(_ string: String, subString: String) -> Bool {
if (string as NSString).range(of: subString).location != NSNotFound { return true }
else { return false }
}
In xCode 11 if you are using sceneDelegate, follow the same logic as described by Malik and Mahesh but use the following function in the SceneDelegate instead:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
//Do stuff with the url
}
}
(instead of application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool)
In details:
First:
Add a url scheme in your project -> info -> url Types -> add url Scheme. Here you can get started by filling the 'URL Schemes" field only (with your app name for instance).
Second:
In your extension, use the following function (called by a button for instance):
let urlString = "MyAppName://host/path"
if let url = URL(string: urlString)
{
self?.extensionContext?.open(url, completionHandler: nil)
}
Third:
Implement your logic in Scene Delegate with:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
//Do stuff with the url
}
}
Swift5
Step1: select project>info>url types>add url scheme
step2: go to the button action method and use this code
let tag = 1
if let url = URL(string: "open://\(tag)")
{
self.extensionContext?.open(url, completionHandler: nil)
}
step 3: welcome you get the control of your host app, jus add this in app delegate method
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
{
if url.scheme == "open"
{
switch url.host
{
case "1":
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
default:
break
}
}
return true
}
Congrats! you open the controller.
I'm working on an existing application which uses the storyboard but I want to continue development without using the storyboard at all, or nib files.
The existing left menu is a UITableView which is not the root controller and does not have a navigation controller associated with it. I have created a UINavigationController in the app delegate and want to use this navigation controller to push a new controller. I am able to present a view controller but I want to use push in order to conform with the current UIX.
In the following code nothing happens because navigationController? returns nil.
Here is my new code in the app delegate.
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
navController = UINavigationController()
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window!.rootViewController = navController
self.window!.backgroundColor = .red
self.window!.makeKeyAndVisible()
let menuViewController = SideMenuViewController()
menuViewController.navController = navController
Then in my side menu controller:
import UIKit
class SideMenuViewController: UIViewController {
var navController: UINavigationController?
.......
let myViewController = myViewController()
self.navigationController?.pushViewController(myViewController, animated: true )
From the UIViewController documentation:
var navigationController: UINavigationController?
The nearest
ancestor in the view controller hierarchy that is a navigation
controller.
Which means when you call self.navigationController in a view controller you get the (nearest) navigation controller that self is embedded in. Apparently your menu controller is not embedded in the navigation controller hierarchy. Using your app delegate's navController member is one way to make this work. Then you can say in your menu view controller:
func menuItemFooSelected()
{
let navController = (UIApplication.shared.delegate as! AppDelegate).navController
let myViewController = myViewController()
navController?.pushViewController(myViewController, animated: true)
}
Alternatively (and probably preferably), when you set up your initial structure in your app delegate, inject the navigation controller into the side menu controller:
class MenuViewController: UIViewController
{
var navController: UINavigationController?
...
func menuItemFooSelected()
{
let myViewController = myViewController()
self.navController?.pushViewController(myViewController, animated: true)
}
}
In application(_:didFinishLaunchingWithOptions:)
...
let menuViewController = MenuViewController(...)
menuViewController.navController = navController
I am using google login frameworks as per the document
func application(application: UIApplication,
openURL url: NSURL, options: [String: AnyObject]) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url as URL!,
sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
It is giving error
Ambiguous reference to member 'subscript'
Request help regarding this.
I think for iOS 9.0 and prior, you should use this method .. check this answer
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])-> Bool {
return GIDSignIn.sharedInstance().handleURL(url,
sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: [:])
}