Building Widgets for iOS development

Source: Internet
Author: User
Tags notification center

With the iOS 8 system up to 4000 API updates are also available today Extension. For iOS, today's Extension developers can provide customized, additional functionality by using system-provided access points for system-specific services. What does that mean? Attempts to open from iOS 7 to the now iOS 8 update have finally opened widget access to developers, which means that system applications and third-party applications can interact within the notification hub (Notification center).


Notification Center Widget [Via Apple]

In fact, compared to Android, because its unique open widget plugin has been developed for many years, with very high freedom of customization, In the new version of Android, you can even put some plugins on the lock screen. And Google and the major software vendors to create a widget plug-in can also be very good and the overall style of the system seamless fusion, and until now in iOS 8 version, the widget can only be placed in the Notification center ( Notification Center) Today in the notice bar, as opposed to Android also heard a lot of people regard this as "iOS is not open" a strong basis. In fact, Apple is also on iOS Human Interface The guidelines mentions:

The center of the developer in IOS 8 should not change, it should still be around the app. Providing excellent interactivity and useful functionality in the app is now, and will be, the core task of IOS app development in the future. Widgets cannot exist in a separate form in IOS, and must be packaged with an app.

From this side, Apple has always been cautious about openness and is open to trying to ensure the integrity of the overall experience, although iOS widgets are too low for Android customization But based on Apple's current openness, it's a great way to control the better integration of widgets and systems. Though dancing in chains, they can capture people's hearts.

From the user's point of view, the interaction of the message can be processed without having to open the application, so that it effectively improves the user's operational efficiency in many scenarios. For example, quickly reply to an email in the widget, complete the TODO schedule on the fly. This interaction has redefined the message from a more macroscopic perspective, The Notification Center (Notification Center) can also act as the next action by acquiring the user's previous behavior (although the open API can only do system-level behavior at the moment). Although the dots are small, the change to user habits is huge.


Widget on Hands [Via Yalantis]

Some people see this is sure to ask why the Windows Phone platform is not mentioned? Because no matter the number of quick entry from the Notification center or the point that can be interacted with, the current situation of WP is "poor white", you want to walk through the WP7 era users do not know what the notification Center is, It takes a full two years to WP8, and those who are bored by other platforms are accustomed to notifying the center of interaction, like this:


WP Notification Center [Via Pcggroup]

You just look at this static picture, that is to stay just to look at the level (in addition to delete operations), MS for notification Center Now the latest news is that the future will support similar to the Notification Center directly reply SMS and other interactions, as to when can wait, who knows.

Say so much and return to the chase.

1. Interaction

Before we start building widgets, if you want to have a complete overview of the widget's technical details and interactivity, I don't think there's any document Extension programming than the official app. The guide is worth reading. Just getting started with the iOS Notification Center has been wondering why the notification Center uses two different tab "Today" and "notifications" to separate messages. Actually, this is related to the widget working mechanism.

The widget is placed in the "Today" tab, and its working mechanism is only when the User dropdown Notification Center will be refreshed to get the latest data, this practice differs from Android, Android is more inclined to keep the entire widget in real-time, continuous updates in the background. Imagine, if we look at the same weather information, Android will continue to consume resources to do a user does not preview the information in real time, This can also explain why Android users are constantly complaining about power consumption. For instant messaging, the iOS approach is to categorize these messages in real-time into the Notifications tab. In fact, this is a good way to solve the problem of using the least resources to ensure the flexibility of its operation.

Because existing widgets are generally present at the system-level UI, Apple makes the following explicit requirements for widget interactions in App Extension Programming Guide:

The extension should be lightweight, fast, and focus on a single function, without interrupting or interrupting the user's use of the current application to complete its own function points.

Like always beloved Todo application clear is an exemplary interaction:


Clear ' s Widget

Of course if the point of the brain will find that the widget open iOS on the implementation of the application between the Launcher became possible, similar to the early has been the magic of the application of "Launcher":


Launcher ' s Widget

Can be used in the IOS Notification Center, a similar application shortcut to quickly switch the app's gadget, in fact, it was not long after the launch of Apple to "misuse/abuse" Widgets as the reason for the next rack, but the interesting just a few days ago March 20 again shelves.

2. Build

In the Widget technology implementation details, it is not intended to browse through all the technical details in this article, and I will only write a solution that I personally (in fact, a beginner) thinks is worth writing, or spends some time finding some problems.

2.1 Pure Code Building

The template for the Today extension create Widget is already supported in Xcode 6, which creates the Maininterface.storyboard file by default to build the UI:


StoryBoard UI

Of course for a pure code of the fans, it is necessary to directly delete the storyboard file in a pure code to build, after the deletion after the notice needs to find supporting files below the Info.plist in the Nsextension field do the following two actions:

A: Delete the Nsextensionmainstoryboard field directly

B: Add the Nsextensionprincipalclass field and set it to Todayviewcontroller

As follows:


After modification

Note When you create a widget with the Xcode default template, the Viewcontroller file name is automatically set to "Todayviewcontroller". Of course, this Viewcontroller name can be modified, The only notable modification of the Viewcontroller file is to set the value of the Nsextensionprincipalclass to be consistent with it. Otherwise the widget will not be able to find the corresponding entry when compiling.

2.2 Left Interval

When you first add a UI element to a real machine to run the widget, you will find that there is always a distance between the widget's left and the screen, causing the layout to be adjusted and the gap far away, similar to this:


Left interval

In fact, this problem is mainly because the widget inside the view by default will have a certain distance between the interval, you can cancel the interval as follows, so that the layout area fills the entire widget:


Cancel Interval

This way the entire layout fills the area interval is set to 0, of course, the more concise way is you can directly adopt "return Uiedgeinsetszero;" The way. The layout of the widget is based on the relative layout of the masonry framework, which is simple and quick to recommend. Of course, the masonry framework has to be recommended to read masonry introduction and use Practice (Quick Start AutoLayout).

2.3 Full Click area implementation

As you can see, when the user pulls the widget, because the widget relies on the application to be packaged with the application when it is distributed, it is desirable to click on any area of the widget layout to evoke the main application, and the usual way to add tap event subscription processing throughout the view:


Tap Event

But this is an extra problem, and if there is no UI element in the widget's blank area to trigger the event, there's a little trick to fix the problem, and you can add a transparent imageview to the whole widget:


Set transparency

When initializing the ImageView transparency to a minimum of 0.01, it is not visible to the naked eye regardless of the setting of its background color. Then use the masonry frame layout to populate the widget with the entire background as follows:


Fill the entire background

Then add a Tap event subscription for ImageView:


Increase Event Subscription

This will enable the entire widget area to be clickable. In addition, the method of invoking the main application through widgets is currently supported only by URL scheme. It is also one of the channels for widgets to feed back data and interactions to the main application.

2.4 Timing Update mechanism

The widget's own update mechanism updates the data as soon as the user pulls down the notification Center (Notification center), but when we look at the widget user's use of the scene, we find that if the user locks the screen too long, nothing is done after the widget is opened, This time for some instant class applications, similar to our weather may involve disaster warning it requires that the scene data once produced will be presented to the user in real time, which requires us to deal with the problem of automatic updating of weather data in this scenario based on the widget's own mechanism.

This time we need to build a regular update of the Nstimer:


Initialize Nstimer

Very simply, the method call that is performed at the Nstimer fixed update interval is updating the data method, but the focus is not here Instead, it triggers and shuts down the nstimer timing. According to the widget lifecycle, if the user is the first drop-down to view the widget is actually performing the entire Viewcontroller lifecycle call process, this is not a problem, but there is still a special case. System in order to guarantee the data on the widget is updated in a timely manner, and the snapshot of the last successful widget is truncated by default. This note has been saved until the new data or UI is updated to be replaced, which brings up a problem when you drag the Notification Center (Notification centre) down too frequently, Debug trace Code execution path you will find that the entire widget life cycle execution process and the first drop-down path of execution have changed.

The first pull-down execution path is viewdidload->viewwillappear, and if the drop-down is too frequent you will find that the code execution path directly executes the viewwillappear method, This is where the system defaults to saving the last snapshot, resulting in a change in the execution path. This will have an impact on the timing of the Nstimer update and the widgets that will be mentioned later.

So obviously, in order to ensure that the timing update mechanism works regardless of the user's operation, we need to put the Nstimer fire trigger code call into the viewwillappear method. Similarly, when the widget is closed The Viewdiddisappear method cancels the Nstimer invalidate timed update.

2.5 Widget Horizontal screen support

About widget cross-screen support in the development of a little time to solve this problem, on the iphone 6 & Plus has been a vertical screen switch, the widget default is Portrait screen, but if you need a horizontal screen UI layout and vertical screen layout is completely different, At this point, you need to determine the current widget's screen state to toggle the corresponding layout.

Of course, the general idea we will follow the end of the process of processing the widget, if you go through the official development document, you will find in iOS 6.0 before the Uiviewcontroller between the screen and the switch, only need to set The shouldautorotatetointerfaceorientation function can be. Uiinterfaceorientation is the enumerated type defined in the UIApplication.h header file, which has a total of four directions. In shouldautorotatetointerfaceorientation Returns the corresponding result in the method, all directions will be supported if you return yes directly. After iOS 6.0, the Uiviewcontroller switch between the vertical and horizontal screens requires more than one supportedinterfaceorientations The Uiinterfaceorientationmask function returns the enumeration type. In addition to setting up shouldautorotatetointerfaceorientation, the direction returned by the supportedinterfaceorientations is consistent with the shouldautorotatetointerfaceorientation , Otherwise it will be in two support different vertical screen viewcontroller switch, there will be horizontal screen, horizontal display of the situation of vertical screen. But the question is, does this approach apply to widget horizontal screen processing?

Use Uideviceorientationisportrait to determine:


Judging the horizontal screen method one

When you perform this code debugging you will find that The value of the orientation direction will always be uideviceorientationunknown. If you open the Uideviceorientation enumeration you will see. It contains two flat-headed uideviceorientationfaceup and Uidevic Eorientationfacedown, In fact it represents the meaning of the screen facing up or lying down in two directions of judgment. So when your device is lying flat on the desktop. Instantly you have switched the horizontal screen sometimes you will find it will return Faceup or facedown, so when you call the Uideviceorientationisportrait method it returns the value actually no Meaning, because the device is now in the direction of lying faceup and facedown are neither horizontal nor vertical. Isn't there a better way?

You can use the following methods to perfectly solve the problem of the widget screen switching state judgment:


Widget screen status judgment

In fact, when you set the widget display height, you will find that the height in the screen state switch will not change, but the width of the screen will change with the state switch, So it is advisable to judge the width of the screen. Because the layout of the UI is different, the call timing can be chosen in the Viewwilllayoutsubviews or Viewdidlayoutsubviews method. Because both of these methods are viewwillappear methods that are necessarily executed, This naturally avoids the problem that the widget itself causes layout updates because of a drop-down snapshot save mechanism that causes the code execution path to change.

2.6 Widget Internationalization

Speaking of this widget internationalization, because our client already supports three different languages, This is where the widget is also required to have international support depending on the language changes in the end. In fact, we have already done a complete set of internationalization mechanism. The best way to deal with widgets is to reuse the in-house mechanism, without the need for individual development support. IOS 8 newly introduced self-made framework Way to organize code that needs to be reused so that the app and widgets can use the same code after linking the framework. Contains the data requests in the widget and other code that can be reused for data memory.

That's what we were going to do at the outset, but we found that stripping this part of the code is significantly more time-out than we expected. So in the international processing of our widgets to do a set of international processing, it and the end of the processing mechanism is not much different:


Widget International Processing

Of course the focus is no longer on its implementation, you can find our widget in the internationalized text file locallizable.string named added a "WG", The problem is that at the beginning of the development we have been thinking that the widget is independent of the main application as a side. So it was understood that only the "locallizable.string", which was named after the file, was normal and could be identified, but when we debugged it, we found that When the widget is packaged, these internationalization will be placed separately under the plugins file, giving a simplified Chinese full path:

/private/var/mobile/containers/bundle/application/61c637ff-b5bc-432a-add5-ba64ebfe98e8/mojiweather.app/plugins /mojiwidget.appex/zh-hans.lproj

Depending on the path you will find the file can be found, but when debugging found that the internationalization of the corresponding key value has been not available, but we arbitrarily "locallizable.string" when there is no problem, and later we found that when we packaged on different models to test the problem, if " Locallizable.string "Name naming will cause the debugging to be OK, and the final packaging will appear to be unable to find the corresponding key is worth the problem. That's why I've never found a specific reason to write this blog. So we give the solution is to be sure and the main application" Locallizable.string "can be resolved by keeping it different.

Of course, the problem of flashing in the widget, because our widget has two different size switch, resulting in this problem is obvious, the process is naturally viewwillload way to do the widget height in different scenarios to initialize the height can be perfectly avoided. Do not repeat this here.

As above only we solve the widget to encounter some big and small problems. The way to solve the problem is not to give details, but the idea is there. There is no clear can post comments @ I can.

  • App Extension programming Guide:today-describes How to develop a app Extension, which is a executable that provides F Unctionality to other Apps.chenkai? developer.apple.com→
  • iOS Human Interface Guidelines:app extensions-provides guidelines for designing the user Interface of an IOS App.chenka I? developer.apple.com→
  • Pushing Ios-here ' s the stronghold and I ' m The little bunny who can barely move around a sword going straight for it. If anyone sends me a picture of a bunny me that can ' t move around a sword against a giant Apple stronghold castle ... I ' m putting it right here! Windchenkai? jaymachalani.com→
  • Ios-get Device Current orientation (App Extension)-Stack overflow-it gives me right orientation but still not Get as Device is Landscapeleft or landscaperight as well as Portrait or Portraitupsidedown.chenkai? stackoverflow.com→
  • Ios-what is the best of the Detect orientation in an app extension? -Stack Overflow-what is the best detect a device's orientation in an application extension? I have had mixed results with solutions I ' ve found on Here:chenkai? stackoverflow.com→
  • ios-detecting tap anywhere on widget? -Stack overflow-i am trying to detect when a user taps anywhere within my Today Extension widget. Currently I has a tap gesture recognizer on the primary view which contains all the labels displayed within the widget. However, with the configuration, only taps on Thechenkai? stackoverflow.com→
  • Why do you need to Develop a widgets for Your iOS (Iphone-one of the updates introduced with the launch of iOS 8 is long an Ticipated Mobile Widgets for the Third-party apps for IPhone and IPad. Probably, the fact that Android devices has been hosting those little application components on their home screens Fochen Kai? yalantis.com→
Recommended expand Reading

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Building Widgets for iOS development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.