Widgets in iOS

Hey buddies, Am back with some interesting concepts of swift and SwiftUI. Here i made a blog on creating widgets for our own app with the help of iOS 14.0+. This one supports for simulator too. Here is the way to implement the widget with cryptocurrency data.

lyvennitha sasikumar
4 min readSep 15, 2021

Here i used a open API on cryptocurrency data. Here is the GET URL for getting crypto currency Data. Coingecko — https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false Provide way to do this.

Start with implementing TableView list of currencies.

Here i had implemented list with amount. Now we can add any one of the coin data to widget.

Here is the API service file for calling this.

enum NetworkConstants: String{case baseURL = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"case httpMethod = "GET"}
struct APIService{static var shared = APIService()func getCryptoData(completion: @escaping(Result<[CrytoCurrencyResponseElement], Error>) -> Void){var urlRequest = URLRequest(url: URL(string: NetworkConstants.baseURL.rawValue)!)urlRequest.httpMethod = NetworkConstants.httpMethod.rawValueURLSession.shared.dataTask(with: urlRequest){ (data, response, error) inif let data = data {let jsonDecoder = JSONDecoder()let empData = try! jsonDecoder.decode([CrytoCurrencyResponseElement].self, from: data)completion(.success(empData))}else{completion(.failure(error!))}}.resume()}}

Now I will tell how to add widget.

Add widget extension from the extension lists and choose activate. And i am gonna write widget using swiftUI. And am gonna store data to userdefaults to show the data.

One thing you have to get in mind is App Groups. This is the one where we can able to share API data from our main app to widgets.

We have to add it in capabilities in AppleDeveloper Account.

Choose App groups underidentifiers.Now that you’re on the Identifiers for App Groups page, click the plus-sign-inside-the-circle button. On the Register a New Identifier page that comes up, the App Groups radio button will be auto-selected, like this:

Make sure you have added app groups to all of your targets.

And it creates a new entitlement and now add the group id with bundleID.

Now we can share the data between main app and widgets. Here i share the data with UserDefaults with suitename and share the data with widget.

After getting data from API i save the the data in a way where we can able to share userDefaults with our widget too.

if let userDefaults = UserDefaults(suiteName: "group.com.<YourbundleID>") {
//I saved dogecoin data to show in widget
userDefaults.setValue(filterData[0].name, forKey: "CryptoName")userDefaults.setValue(filterData[0].currentPrice, forKey: "CryptoPrice")}

Now we can get this values in widget extensions. Am using SwiftUI for widget extension and i assign value to a @State variable.

@State var data = UserDefaults(suiteName: "<YourBundle>")?.value(forKey: "CryptoName") as? String@State var price = UserDefaults(suiteName: "group.com.<YourBundleID>")?.value(forKey: "CryptoPrice") as? Double

I created the design with image and two texts along with time.

var body: some View {  VStack{    HStack{     Image("Doge")      .resizable()      .frame(width: 100, height: 100)     VStack{       Text(data ?? "No data found")       Text(String(price ?? 0.0))     }    }   Text(entry.date, style: .time)  }}

Now steps to add widgets we created are here.

Go to widget section and tap on edit. All the widgets are shown in editable mode.

Now tap on plus icon on top left corner of the screen. That shows a list app of app which have widget extension.

In that list crypto app is our app. Click that and popup for activating widget will be shown

Am gonna add medium sized widget to my widget list and tap on activate.

Now the widget of our own app will be visible in widget section. Don’t forgot to add app groups. Its the main key. Otherwise it won’t work.

HAPPY CODING!💨

--

--

lyvennitha sasikumar

Passionate iOS developer chasing my dreams toward success