Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing WidgetCenter from Objective-C App

I have an existing Objective-C app and have developed a SwiftUI iOS 14 Widget for it. So far so good. Now I am trying to reload the timeline from my Objective-C app. I understand that there are no Objective-C api for accessing WidgetCenter, so I have implemented the bridging steps outlined in Apple's documentation (at least I think I have since I am totally new to Swift). I cannot seem to be able to get Widget Center nor WidgetCenter.shared.reloadAllTimelines()recognized in my Objective-C app. I have tried many approaches with no success, so I must be doing something wrong. Any help or suggestions would be greatly appreciated.

like image 825
grwilde Avatar asked Aug 10 '20 03:08

grwilde


People also ask

Is Objective-C discontinued?

Thus, we can say that Objective C is going to stay around in the foreseeable future, and the Objective C developers who have mastered this language may rest assured that their skills will continue to be in demand. However, it is a different story with new apps and young developers choosing the language to learn.

Is Objective-C deprecated?

It won't be deprecated, but it'll move to Florida to enjoy its golden years. It'll spend days running the legacy app with a million lines of code, and its nights sipping margaritas with the OAuth library everyone fears rewriting.

Can you still use Objective-C?

Objective-C is so pervasive in iOS that it's impossible to completely remove it. Apple continues to maintain libraries written in Objective-C, so we should expect Objective-C to be treated as a (mostly) first class language in iOS. At other companies, legacy code remains.

How do I import a swift file into Objective-C?

Import Swift code into Objective-C within the same framework: Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .


1 Answers

I faced with the same issue. The solution for this was to create a swift file for example: WidgetKitHelper. Create the assigned swift-objc header with that too (bridging header file) if it not generated automatically you can add it by manually (search for it). In the helper object you can get access to widgetkit, and if you do the rest to be able to see the swift code from your objc code, you can use this as a wrapper.

Tips:

import WidgetKit

@available(iOS 14.0, *)
@objcMembers final class WidgetKitHelper: NSObject {

    class func reloadAllWidgets(){

        #if arch(arm64) || arch(i386) || arch(x86_64)
        WidgetCenter.shared.reloadAllTimelines()
        #endif

    }
}

obj-c code:

First import the swift code by adding:

#import "YourProjectName-Swift.h"

Then you can use:

[WidgetKitHelper reloadAllWidgets];
like image 144
incmiko Avatar answered Oct 25 '22 15:10

incmiko