Build widgets for iOS development and build widgets for ios

Source: Internet
Author: User
Tags notification center

Build widgets for iOS development and build widgets for ios
Source: Chen Kai's blog at jianshu (@ chenkaiHome) Welcomes the original article to bole headlines

With the update of up to 4000 APIs in the iOS 8 system, there is also the Today Extension. for iOS, with Today Extension, developers can use the access points provided by the system to customize services for the system and provide custom additional functions. what does this mean? From the attempt to open the path in iOS 7 to the arrival of iOS 8 update, the Widget access is finally made available to developers. This means that both system applications and third-party applications can interact with each other in the Notification Center. notification Center Widget [Via Apple]

In fact, compared with Android, its unique open Widget plug-in has been developed for many years and has a high degree of customization. In the new Android system, some plug-ins can even be placed on the screen lock page. the Widget plug-ins made by Google and major software vendors can also be seamlessly integrated with the overall style of the system, and until now in iOS 8, widgets can only be placed in the Notification Center today's Notification bar. Compared with Android, many people have heard this as a powerful basis for "iOS is not open enough. apple also mentioned this in iOS Human Interface Guidelines:

The Developer Center in iOS 8 should not change, but should still be around the app. it provides excellent interaction and useful functions in apps. Now, it will be the core task of iOS application development in the future. In iOS, Widgets cannot exist in a separate form. They must be packaged with an application.

From this perspective, Apple has always been cautious about opening up. The purpose of opening up is to ensure the integrity of the overall experience. Although iOS widgets are less customizable than Android, however, based on Apple's current degree of openness, it can effectively control the better integration of widgets and systems. although it seems to be dancing in handcuffs, it can capture the hearts of the people.

From the user's perspective, the interaction feature that can process messages without opening the application makes it effectively improve user operation efficiency in many scenarios. for example, you can quickly reply to an email in a Widget to complete the Todo schedule in real time. in this interaction, more messages are redefined from a macro perspective. The Notification Center obtains the previous user behavior, it can also undertake the next behavior (although currently open APIs can only achieve system-level behavior ). although the point is small, it is a huge change in user habits. widget on hands [Via Yalantis]

Some people will certainly ask why Windows Phone is not mentioned? Regardless of the number of quick portals in the notification center or the point of interaction, the current situation of WP is "one sentence, one sentence ", it takes two years for you to figure out what the user did not know about in the WP7 era, those who are tired of playing by other platforms and want to get used to the interaction between the notification center, like this:

WP notification center [Via PCGGroup]

You just look at this static image, that is, you just need to look at the degree (except for the delete operation ), for the latest message from the notification center, MS will support interaction such as replying to text messages directly from the notification center in the future. Who knows when to wait.

After talking so much, let's get back to the question.

1. Interaction

Before building a Widget, if you want to have a complete overview of the technical details and Interaction Features of the Widget, I think there are no documents worth reading more than the official App Extension Programming Guide. when I first started to contact the iOS notification center, I was wondering why the notification center used two different tabs "today" and "notification" to separate messages. in fact, this is related to the working mechanism of widgets.

The Widget is placed in the "Today" Tab, and its working mechanism is that the latest data is refreshed only when the user pulls down the notification center. Unlike Android, android is more inclined to keep the entire Widget updated in real time on the background. imagine that if we look at the same weather information, Android will continue to consume resources, so that a user will not preview the information in real time. This will explain why Android users often complain about power consumption. for instant messages, iOS directly classifies these messages into the "Notification" Tab in real time. in fact, this approach is a good solution to ensure the flexibility of its operations with the minimum resource consumption.

Because the existing widgets are generally displayed on the system-level UI, Apple puts forward the following clear requirements for Widget interaction in App Extension Programming Guide:

Expansion should be lightweight and fast, and focus on a single function, without interrupting the user's use of the current application.

Similar to the always-love Todo application, Clear is an interactive model: Clear's Widget

Of course, if you move your mind, you will find that it is possible to enable Launcher between apps on iOS by using widgets. For example, the early magic app "Launcher": Launcher's Widget

In the iOS notification center, you can use a shortcut similar to an application to directly switch the App's gadgets. In fact, not long after the launch, it was removed from the shelf by Apple for "misuse/misuse" Widgets, But it was interesting that it was re-launched a few days ago in March 20.

2. Build

In terms of the Implementation Details of the Widget technology, I am not going to go through all the technical details in this article. I will only write my personal information (actually a beginner) points that are worth writing and error-prone points or time-consuming solutions to some problems.

2.1 code-only Construction

Xcode 6 already supports Today Extension to create a Widget template, which will create a MainInterface. storyboard file by default to build the UI: StoryBoard UI

Of course, for a pure-code fan, the storyboard file must be directly deleted and constructed in pure-code mode. After deletion, note that the Info under Supporting Files must be found. the NSExtension field in plist performs the following two operations:

A: directly Delete the NSExtensionMainStoryboard field.

B: add the NSExtensionPrincipalClass field and set it to TodayViewController.

After modification

Note that the ViewController file is automatically named as"TodayViewController". Of course, the ViewController name can be modified. the only thing worth noting is that after you modify the name of the ViewController file, you also need to set the NSExtensionPrincipalClass value to be consistent with it. otherwise, the corresponding entry cannot be found during Widget compilation.

2.2 left-side Interval

When the first time you add a UI element to run the Widget using a real machine, you will find that there is always a gap between the left side of the Widget and the screen, resulting in a great gap between the layout adjustment and the left side, similar to the following:

In fact, this problem is mainly because the view in the Widget has a certain distance between the left and the bottom by default. You can use the following method to cancel the interval so that the layout area fills the entire Widget:

Cancel Interval

In this way, the padding interval of the entire layout is set to 0. Of course, you can directly use the"Return UIEdgeInsetsZero;"Method. the relative layout of the Widget layout processing is implemented using the Masonry framework, which is simple and quick to recommend. of course, for the Quick Start of the Masonry framework, you have to read the introduction and use practices of Masonry (Quick Start With Autolayout ).

2.3 Implementation of the entire click Area

As you can see, when the user opens the Widget, because the Widget is dependent on the application package together with the application during distribution, and you want to click the Widget layout in any area to evoke the main application, you can use the following methods to subscribe to the entire View:

Tap event

However, this method will cause an extra problem. If the blank area of the Widget does not have any UI elements, this event cannot be triggered. Here is a tips to solve the problem, you can add a transparent ImageView for the entire Widget:

Set transparency

During initialization, make sure that the imageview transparency is set to the minimum value of 0.01. No matter why the background color is invisible to the naked eye, use the Masonry framework layout to fill the entire background of the Widget as follows:

Fill in the entire background

Then add a Tap event subscription for the imageview:

Add event subscription

In this way, you can click the effect in the entire Widget area. in addition, only url scheme is supported for calling the main application through widgets. it is also one of the channels for widgets to feedback data and interaction to the main application.

2.4 timed update mechanism

The update mechanism of widgets updates data immediately when users pull down the Notification Center. However, when we carefully study the usage scenarios of Widget users, we find that if the screen lock time of users is too long, do not perform any operations after opening the Widget. This is applicable to some real-time applications. For example, disaster warning may be involved in the weather. It requires that the scenario data be displayed to users in Real Time Once generated, in this case, we need to deal with the automatic updating of weather data in this scenario based on the Widget mechanism.

In this case, we need to build a timed update NSTimer:

Initialize NSTimer

It is very simple. The method call at the fixed update interval of NSTimer is the data update method. Of course, the focus is not here, but the time to trigger and disable this NSTimer. according to the Widget life cycle, if the user pulls down the Widget for the first time and actually executes the entire ViewController Life Cycle call process, there is no problem, but there is still a special situation. to ensure that the Widget data is updated in a timely manner, snapshots of the last successfully displayed Widget are taken by default. this snapshot will be retained until new data or UI is updated. This will cause a problem. When you drag the Notification Center drop-down too frequently, debug tracks the code execution path and you will find that the entire Widget lifecycle execution process and the path for the first drop-down operation have changed.

The first drop-down execution path isViewDidLoad-> viewWillAppearIf the drop-down is too frequent, you will find that the Code Execution path will only executeViewWillAppearThis is the change in the execution path caused by the system saving the last snapshot by default. This will affect the NSTimer Update Time and the processing of widgets that will be mentioned later.

Obviously, in order to ensure that this regular update mechanism can take effect no matter what circumstances the user can perform, we need to put the nst1_fire trigger code callViewWillAppearMethod. Similarly, when the Widget is disabledViewDidDisappearMethod to cancel the scheduled update of NSTimer invalidate.

2.5 Widget horizontal screen support

The horizontal screen of widgets can be used to solve this problem by a little time in development. On the iPhone 6 & Plus, the horizontal and vertical screen has been switched directly. By default, the Widget is a vertical screen, however, if the layout of the landscape UI is different from that of the landscape screen, you need to determine the status of the current Widget to switch the corresponding layout.

Of course, the general idea is that we will process widgets in the client-side way. If you go through official development documents, you will find that UIViewController switches between portrait and landscape screens before iOS 6.0, you only need to setShouldAutorotateToInterfaceOrientationFunction. UIInterfaceOrientation is the enumeration type defined in the UIApplication. h header file. There are four directions in total.ShouldAutorotateToInterfaceOrientationThe method returns the corresponding results. If YES is returned directly, all directions are supported. However, after iOS 6.0, you need to set one moreSupportedInterfaceOrientationsThe function returns the UIInterfaceOrientationMask Enumeration type.ShouldAutorotateToInterfaceOrientationIn additionSupportedInterfaceOrientationsReturned direction andShouldAutorotateToInterfaceOrientationOtherwise, when two viewcontrollers support different horizontal and vertical screens, the landscape is changed to landscape and landscape is changed to landscape. but the question is, is this method applicable to the Widget landscape processing?

Use UIDeviceOrientationIsPortrait to judge:

Method 1

When you debug this code, you will find that the orientation value will always be UIDeviceOrientationUnknown. if you click UIDeviceOrientation, you will see it. it contains two flat directions: UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown. In fact, it indicates that the screen is facing up or lying down in two directions. so when your device is on the desktop. if you have switched the landscape screen, you will find that it will return FaceUp or FaceDown. Therefore, when you call the UIDeviceOrientationIsPortrait method, the returned value is meaningless, the reason is that Faceup and FaceDown are neither landscape nor landscape screens. is there no better way?

You can use the following methods to determine the switching status of widgets:

Widget portrait status judgment

In fact, when you set the Widget to display the height, you will find that the height switch in the horizontal and vertical screen status will not change, but the width will change with the horizontal and vertical screen status switch, therefore, it is advisable to judge the screen width. because the horizontal and vertical screen UI layout is different, the call time can be selected in the viewWillLayoutSubviews or viewDidLayoutSubviews method. because both methods are inevitable, the viewWillAppear method naturally avoids the layout update problem caused by the Code Execution path change caused by the drop-down snapshot storage mechanism of the Widget.

2.6 Widget Internationalization

Let's talk about how to internationalize This Widget, because our client already supports three different languages. This means that the Widget must be internationalized according to language changes in the client. in fact, we have developed a complete set of internationalization mechanisms. the best way to process widgets is to reuse the internal mechanism without independent development support. iOS 8 introduces a self-made framework to organize code that needs to be reused, so that apps and widgets can use the same code after the framework is linked. contains data requests and data memory in widgets and other code that can be reused.

This is the solution we planned to solve at the beginning, but we found that the time cycle of code stripping obviously exceeded our expectation. therefore, in terms of internationalization, our Widget has made a set of internationalization processes independently. It is not very different from the intrinsic processing mechanism of the client:

Widget Internationalization

Of course, the focus is no longer on its implementation. You can find that Locallizable is an internationalized text file in our widgets. A "WG" is added to the string name. At the beginning of development, we always thought that the Widget as the end is independent from the main application. so it was understood that only the file named "Locallizable. string is normal and can be identified, but we found during debugging that the Widget packaging will put these internationalization separately under the PlugIns file, here is a full path of Simplified Chinese:

/Private/var/mobile/Containers/Bundle/Application/61C637FF-B5BC-432A-ADD5-BA64EBFE98E8/MojiWeather. app/PlugIns/MojiWidget. appex/zh-Hans.lproj

According to this path, you will find the file that can be found at the time of debugging. However, when debugging, you find that the value of the corresponding Key for internationalization cannot be obtained all the time, but we can choose any non-"Locallizable. "string" is no problem, and then we found that when we package on different models to test this problem, if "Locallizable. the name of string will lead to OK during debugging, and the corresponding key cannot be found in the package. this is because I have not found any specific reason for writing this blog. therefore, the solution must be "Locallizable" with the main application. string "can be solved by keeping the difference.

Of course, the flash problem in widgets is obvious because our widgets have two different size switches, the processing method is naturally done in the viewWillLoad method, and the Widget height can be perfectly avoided after being initialized in different scenarios. I will not repeat it here.

The above is just a solution to some small and large problems encountered by the Widget. Although the solution does not provide details, there are some ideas. If you are not clear about it, please post it and comment on @ me.

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.