- Original link: IOS 8:creating a Today Widget
- Translator: Harries Chen
- Reviewer: mr.simple
- Status: In proofreading
Creating an extension is an important feature of the IOS8 upgrade, and in this presentation I will explain it in the notification center by creating a custom today component. First, let's take a brief look at the important concept of extensions to understand components.
1. What is an extension?
The extension is a special program. But it doesn't belong to a complete app, it needs to have a container app (containing app) for publishing. The container can be an existing app, or you can create a new one. A container can have one or more extensions. An extension cannot be published independently, it needs to have a container.
The extension is loaded and controlled by the host program (host app) to which it belongs. For example, it can share an expansion like safari, or just like the Today summary of notification hubs and other components. Each extension of the system is called an extension insertion point.
In order to create an extension, you need to add a target to the project file of the container (Cotaining app). The templates provided by Xcode already include the frameworks needed to extend the access point,
2. Today's extended access point
Extensions provide today's extended access points, known as components, that provide easy and quick access to information. The component is associated to the notification hub. It is important to design an easy-to-use component because too much interaction can cause users to be difficult to operate. Be careful not to use the keyboard.
We all want the component to have a nice looking interface and to keep it up to date, so it's important to keep it stable, and you need to make your components fast and resource-efficient. To avoid affecting this user experience, the system terminates the running of the component if the component consumes too much memory. Components need to be simple and focus on displaying what they need to display.
The theory is enough, let's create our own today component, we use it to show the amount of disk usage, to prompt the user through a progress bar. In this process, we will also involve other extensions.
3. Implementation Step 1: Create a project
If you want to create an extension as an already existing app, open the Xcode project and then go to step 2. If you start from scratch like me, you need to create a container program (containing app) first.
Open Xcode in the file directory select New > Project... we use objective-C as development language, select Single View Application template.
Step 2: Add a target
Open the File Table of contents and select a New > Target.... template in Application Extension the category Today Extension .
You will notice that target is added to our current project and the extension will be embedded in the container program. Then the extension will have an identifier like a container program com.tutsplus.Today.Used-Space .
Click Next , give the component a name, for example Used Space , click Finish Create target.. A, Xcode will create a new scheme for you, then ask if you want to activate, click Activate continue.
Xcode creates a group named for Space Used the component and then generates some files in it, one UIViewController and one storyboard , and the component is just one UIViewController and one storyboard , and if you open the header file of the view controller, you will find that it is a generic UIViewController subclass.
If you choose the extended target, open Build Phases and expand Link Binary With Libraries , you will find it added a Notification Centre frame.
4. User interface
We are now going to create a basic user interface, first we need to determine the size of the component, there are two ways to tell the system what size we need. The first is the use of auto layout and the second is viewcontroller the properties used preferredContentSize .
The concept of automatic layout is still available on the component, not only to pay attention to the various widths of the iphone (as well as the ipad and future devices) but also to note that it may be realistic in landscape mode. If the interface is constrained by automatic layout, it is very convenient for developers. The height of the adjustment component can be setPreferredContentSize achieved through.
Step 1: Add elements
Open in the Xcode editor MainInterface.storyboard . You will find that there is already a Helloewworld label already in view, select and delete it, because we will not use it, add a new label and let it align to the right image.
In the Attributes Inspector set color to white, the font alignment is right-aligned, and the text occupies 50%.
Select in the editor Size to Fit Content to have the label automatically adjust the size.
Then add an UIProgressView object to the left position of the label.
Select the progress bar, change to Attributes Inspector Progress Tint white, and change Track Tint to sepia. This will make the progress bar more noticeable, and then add some constraints.
Step 2: Add a Constraint
Select the upper and lower constraints that the label adds. Do not tick Constrain to margins the option.
Select the upper and the left constraints on the progress bar, and don't forget to reverse the selection Constrain to margins .
Because we have changed the constraints, so we will have a small problem to solve, now the progress bar size does not correctly respond to the constraint after the progress bar size, select the progress bar, click Resolve Auto Layout Issues the button, select Update Frames Select Selected Views . This will update the size of the progress bar based on the constraint.
Step 3: Build and run
It's time to take a look at our components, 择Used Space schem choose E, select a Prodect table of contents Run or press directly Command-R , pull down the notification center, and then click the edit button below, your today component will appear in the place where you can add, click on the Add button to the left of it.
That's what our expansion looks like.
It looks good, but why is there so much space underneath? Why does the operating system not adhere to the progress bar constraints?
This problem is caused by the standard spacing of the operating system, and we'll change it next, so keep in mind that the left margin of the progress bar is aligned with the name anyway.
If you choose your device or run it on another device, you will find that the component is resized, thanks to the automatic layout (auto layouts) we use.
Step 4: Fix the button margin
Open TodayViewController.m . You can see that the controller implements the NCWidgetProviding protocol. This means that we need to implement widgetMarginInsetsForProposedMarginInsets: a method to return a custom margin ( UIEdgeInsets struct), and modify the method as follows.
Run the program again to see the results and find that the bottom margin of the component is smaller, and you can customize these margins to whatever effect you want.
Step 5: Connect the Outlets
Finally, let's add two outlets, open storyboard , switch to dual editor mode to ensure the reality TodayViewController.m .
Press Control and drag the label to viewcontroller the interface section to create the label's interface, named percentLabel , to repeat the process for UIProgressView creation barView .
5. Show Real Data
We will use the NSFileManageer class to calculate the available space for the device, so how do we update the component's data?
This is NCWidgetProviding another way to deal with it. The operating system will invoke the widgetPerformUpdateWithCompletionHandler: method when the component is loaded or entered from the background. Even if the component is not visible, it is possible for the system to load and update it and save the snapshot, which will be displayed the next time the component appears, because there will be a short period of time before the component is displayed.
Determine whether new content or data updates need to be called by processing the completion handle. Block has a parameter ncupdateresult to describe whether we want to update the content. If not, the operating system will know that there is no need to save a new snapshot.
Step 1: Define the properties
We need to define some properties to save the remaining, used, and space, and add these attributes to the TODAYVIEWCONTROLLER.M.
Step 2: Implement Updatesizes
Create an auxiliary method updateSizes to pull the necessary data and compute the space utilization of the device.
- (void)updateSizes{ // Retrieve the attributes from NSFileManager NSDictionary *dict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil]; // Set the values self.fileSystemSize = [[dict valueForKey:NSFileSystemSize] unsignedLongLongValue]; self.freeSize = [[dict valueForKey:NSFileSystemFreeSize] unsignedLongLongValue]; self.usedSize = self.fileSystemSize - self.freeSize;}
Step 3: Store
We can use it conveniently NSUserDefaults to store data. The component's life cycle is very short, so we need to cache this value, we can set an initial value to the interface, and then calculate the real value.
This is very helpful for us to update the snapshot of the component, let's create a quick method to access it NSUserdefaults .
Note that we used a macro definition RATE_KEY and don't forget to add it TodayViewController.m .
Step 4: Update the interface
Because our component is a view controller, the viewDidLoad method is good for updating the user interface, and we create a helper method updateInterface to update the interface.
Step 5: Call the completion handle
The changes in the available space lead to the new one too often, in order to determine if we really need to refresh the interface, we calculate the usage and set a lower 0.1% of the update, instead of a change to refresh the interface. Modify the widgetPerformUpdateWithCompletionHandler: following:
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler{ [self updateSizes]; double newRate = (double)self.usedSize / (double)self.fileSystemSize; if (newRate - self.usedRate < 0.0001) { completionHandler(NCUpdateResultNoData); } else { [self setUsedRate:newRate]; [self updateInterface]; completionHandler(NCUpdateResultNewData); }}
After each recalculation, if there is a noticeable change with the last time, save the value and update the interface to tell the operating system. If there is no obvious change, we don't need a new snapshot. If an error occurs, the error will be NCUpdateResultFailed reported, but there is no error in this example.
Step 6: Build and run
Run your program again and it will correctly show how much space you have used.
6 Summary
Let's review the component life cycle, and when we open the Today panel, the system may show the last snapshot knowing that it is ready to complete. The interface will be loaded and the component will take out the cache in Nsuserdefaults to update the user interface.
It is then widgetPerformUpdateWithCompletionHandler: called to recalculate the real value, and if the cached value is similar to the real value, nothing will happen and if there is a difference, the new value will be refreshed by the cache interface.
In the background, the component may be called by the system, and if returned NCUpdateResultNewData , the new snapshot will be created for the next occurrence.
7 add more information and animations
Although we have finished displaying the function of using space, it will have an exact number. To avoid a complex user interface, make the interaction more friendly. If you click on the Percent label, the component will display a new label extra. This is also a great opportunity to learn how to use animations in components.
Step 1: Change the user interface
Open the MainInterface.storyboard Select Label, In the Attributes Inspector under, under View options, locate the User Interaction Enabled option and enable it.
Next, we need to remove the label's bottom constraint. The distance from the bottom of the label view changes, which means that the constraint becomes invalid.
Select Label, Size Inspector expand ' Size ', select the space constraint at the bottom, and click Delete. You can also manually select a constraint in the view to boot and delete it. The label now has only the top constraint, as shown in.
Select the view controller by clicking the first of the three icons at the top of the screen. In Size Inspector the Size , set the height to 106 .
Add a new label, Attributes Inspector set its color to white. Also, set the number of rows 3 , height 61 , width 200 . This should be enough to hold three messages. Keep it on the left and align it down.
The final step is to open the Assistant to edit and create a outlet named Detailslabel.
Step 2: Install
The control will only expand in an instant. We can NSUserDefaults save a Boolean variable to remember the last state, but, for simplicity, it will close each time the component loads it. When you click on the Percent label, additional information will appear.
Let's first define two macros TodayViewController.m to help us set the size. In Viewdidload, add two lines of code to set the initial height of the control, making the label transparent. We will make the detailed label appear when the percent label is clicked.
Note that we set the width of the control to 0, because the width is determined by the operating system.
Update Details tab
In the details label, we use Nsbytecountformatter to show the available, used, and total values. Add the following code to the view controller.
-(void)updateDetailsLabel{ NSByteCountFormatter *formatter = [[NSByteCountFormatter alloc] init]; [formatter setCountStyle:NSByteCountFormatterCountStyleFile]; self.detailsLabel.text = [NSString stringWithFormat: @"Used:\t%@\nFree:\t%@\nTotal:\t%@", [formatter stringFromByteCount:self.usedSize], [formatter stringFromByteCount:self.freeSize], [formatter stringFromByteCount:self.fileSystemSize]];}
Step 4: Detect click events
In order to detect the Click event, we have overridden the method in the attempt touchesBegan:withEvent: . The idea is simple, when a touch event is detected, expand the Details tab and update. Please note that the size of the plugin is in the callingsetPreferredContentSize updated.
Step 5: Add animations
Although this component works well, we can improve the user experience by using the gradient effect in the Show Details tab, which can be accomplished by implementing it viewWillTransitionToSize:withTransitionCoordinator: . This method is called when the height of the component changes. Because this is done through the gradient coordinate object, we can add some extra animations.
As you can see, we've changed the alpha value of the tag, but you can add any type of animation to enhance the user experience.
Step 6: Build and run
We run the program once again. By clicking on the percent label to realistic details label.
Conclusion
These logic seems overly complex for such a simple task, but you will be familiar with creating the whole process of today's expansion. Remember these principles when designing and developing your plug-in. Remember to keep it simple and clear, and don't forget about performance.
There are some quick actions that may not be needed, but it becomes particularly important that you take time-consuming processing. Use the knowledge of your view controller to check whether it works in various screen sizes. It is recommended that you avoid scrolling views or complex touch recognition.
Although the extension will have a separate container, as we saw earlier, it allows the data to be shared between the application and the containing extension. You can also use NSExtensionContext OpenURL:completionhandler: a custom URL scheme to quickly launch your program from the component. If you need to share your extension, create a framework to use your application and extensions.
I hope the knowledge presented here is useful to help create your next great expansion today.
Go from: Https://github.com/bboyfeiyu/iOS-tech-frontier/blob/master/issue-3/iOS today's extension. md#ios8-today
IOS8 Today's expansion