IOS Development Notes 2-Development Department Workflow

Source: Internet
Author: User
Tags exit in notification center

1. Project Manager

After migrating to a new company for hard-pressed development and learning about the various departments of the company, we need to understand the development process of the product department. Just as every project has a project owner (Project Manager), every iPhone program contains a UIApplication object, which manages the lifecycle of the entire program, starting from loading the first display interface, it also monitors the execution of system events and Program Event scheduling throughout the program. Int main (int argc, char * argv []) {

NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
Int retVal = UIApplicationMain (argc, argv, nil, nil );
[Pool release];
Return retVal;
}

In the main function, the second line of code UI Application Main (argc, argv, nil, nil); initializes the UIApplication object, which is implicit, in addition to the argc and argv parameters, this function also has two string parameters to identify the UI Application class and UI Application proxy class. The default value is 2 nil, if the first parameter is nil, the UI Application class is initialized as the default value. You can use the custom UI Application subclass instead of nil. As for the second parameter nil, how can I create another UI Application proxy class object with the UI Application object? Here we need to explain that the UI Application object is to manage the entire life cycle of the program. In fact, it does not do anything specific, it is only responsible for listening to events. When actual work is required, it is handed over to the UI Application proxy class. The UI Application is equivalent to the courier who only communicates commands to the UI Application proxy class, then the soldier is truly involved, so the proxy class needs to be set for the UI Application object.

2. Development Process

The normal development process is to first confirm the requirement, code, test the Department, modify the Bug, and finally release with the project manager. Similarly, for Ios application development, you should also determine the status of the application to determine under what circumstances we should perform logic processing based on business needs. IOS app status machines have five statuses:

1. Not running: the application has Not been started, or the application is running but is stopped by the system on the way.[Do I have to take a rest for mainong? I cannot do it endlessly every day. What if my wife and children die suddenly? What do my parents do? Which of the following companies in China can cook things for you like Google?]

2. Inactive: the current application is running on the foreground, but does not receive events (other code may be executed currently ). Generally, when an application switches from one status to another, the transition will temporarily stay in this status. The only situation where the user remains in this status for a long time is that when the user locks the screen or the system prompts the user to respond to certain (such as phone calls or unread text messages) events.[This process is similar to determining the demand stage with the project manager. We always need to know what to do.]

3. Active: the current application is running on the foreground and receives events. This is the normal status when the application is running on the foreground.[This process is a hard-pressed development phase. We need to work overtime and code. We need to pay for the overtime. We need to repair our car if it breaks down.]

4. Background: The application is in the Background and the code is still being executed. Most applications that are about to enter the suincluded State enter this state for a short time. However, applications that require additional execution time will remain in this state for a longer period of time. In addition, if an application is required to directly run in the Background when it is started, such an application will directly enter the Background state from the Not running state without going through the Inactive state in the middle. For example, applications without interfaces. Note: This does not refer to applications without interfaces. In fact, it can also be interface applications. If you want to directly enter the background status, the application interface will not be displayed.[This process is similar to the Bug test conducted by the testing department, and the testing colleagues have worked hard]

5. sushortded: the application is in the background and the code execution has been stopped. The system automatically moves the application to this status, and will not notify the application before this operation. In this status, the application will still reside in the memory but will not execute any program code. When the system generates a low memory alarm, the system will clear the application in the susponded state out of the memory to provide sufficient memory for the application running on the foreground.[This process is similar to our learning stage when we always encounter a technology we don't know. Most developers are willing to learn it]

For example:

 

3. Status transition

3.1 application startup-Project startup

A. Start a new project

When the application starts, it enters the foreground status from Not running or directly enters the background to run. When entering the front-end, it is actually going into the Active state, and will enter the Inactive state for a short time in the middle. When the application starts, the system will create a process and a main thread, and call the main function in the main thread, that is, the above two mentioned. The main function is automatically generated by Xcode when a project is created. The main function initializes the UIApplication object and sets the UIApplication proxy class. Most of the work before the application is initialized and ready to run in the foreground is completed in the main function.

For example, the method of the called UIApplication proxy class on the right side of the process when the application is started until the foreground is running.

If your application needs to directly enter the backgroundu status after it is started, the corresponding startup process is slightly different from the previous one. The main difference is that the above application enters the active state, your application will go to the background and process the event. When no event is processed, it will be suspended and enter the suincluded state. As shown in.

 

Note that when an application directly enters the background state from the not running state, the system still loads the user interface file if the application has an interface when it is started and enters the background state, it is not displayed on the application window.
To determine whether your program is in foreground or background, you can check the applicationstate attribute of the uiapplication Class Object in application: didfinishlaunchingwitexceptions: method. If the application is in foreground, the property value is uiapplicationstateinactive. If it enters the background, it is uiapplicationstatebackground.

Sample Code for detection:

Uiapplicationstate state = [uiapplication sharedapplication]. applicationstate;
Return (State = uiapplicationstateactive | state = uiapplicationstateinactive );

Note: When an application needs to open a URL, the startup process of such an application is slightly different from the two diagrams in Section 3, as shown in the following code:

An application with a custom URL mode must be able to process all the URLs passed to it. All URLs are passed to the application proxy for processing, whether the current application is in the startup stage, running or background. To process URL requests, your application proxy must implement the following interface methods:

(1) Use application: didFinishingLaunchingWithOptions: To retrieve URL Information and decide whether to open this URL. This method is called only when the application is started.

(2) iOS4.2 or an updated version. Use the method application: openURL: sourceApplication: annotation: to open the file.

(3) For iOS4.1 or an older version, use the method application: handleOpenURL: to open the file.

B. Modify the old project
When a URL request arrives, if your application is not running, it will be started and moved to the foreground to open the URL. Your application: didfinishinglaunchingwitexceptions: method implementation should include retrieving a URL from the options dictionary and determining whether the application can open it. If it can be opened, YES is returned, and the Method application: openURL: sourceApplication: annotation: Or Method application: handleOpenURL: processes the specific URL opening process. The startup sequence of an application that requires opening a URL at startup is shown in:

When a URL request arrives, if your application is running in background or is sudedded, it will be moved to the foreground to open the URL. Soon after, the system will call the application: openURL: sourceApplication: annotation: Method of the application proxy to detect the URL and open it. If your application proxy does not implement this method (or the current system is iOS4.1 or an older version), the system will call the application: handleOpenURL: Method of the application proxy instead. The following describes how to wake up a background or suspended application to open the URL program for execution, as shown in:

Supports custom URL-based applications. You can specify different startup screen images before the application starts and processes the URL. For more information, see "Providing Launch Images for m url Schemes" on the iPhone appprogrammingguide.pdf page 85th ".

3.2Response interruption-Special Tasks

When a warning-based interrupt (such as a phone call) occurs, the application will temporarily switch from active to Inactive to provide the system with an opportunity to notify the user and let the user decide what to do. The application remains Inactive until the user decides how to handle the interrupt warning. After the user makes the selection, the current application can continue to run or return to the active state, or directly switch to the background state for other applications to run. In this case, the application execution process is shown in:

In iOS5, notification is a notification that displays the banner mode. It does not switch the currently active application to Inactive state like the previous interruption. The banner of such notifications is placed on the top edge of your application window, so your application is still active and continues to receive touch events as before. However, if you pull the banner to present the content in the notification center, the current application will switch to the inactive status like the preceding warning-based interruption. At this time, the application will remain Inactive until the user processes the pull banner notification, maybe only clearing the notification or starting another application. The current application either switches back to the active status to continue running or to the background status. You can use the Settings application to configure which Notifications are displayed as banner and alert warnings.

Pressing the "sleep/Wakeup" Key is another type of interruption, which causes the application to be deactived. When the user presses the "sleep/awake" key, the system can not touch the event, deactivate the current application and lock the screen. For applications that use data protection for encrypted files, the lock screen event includes the deactivated application and the touch event.

What will happen when an interruption occurs?

A warning-based interruption will cause the user to temporarily lose control of the application. The current application continues to run in the foreground, but does not receive any touch events. (In fact, the application only does not receive touch events. Other types of events, such as accelerometer events and notification notifications, are still received by the application .) To respond to these changes, the application must do the following in applicationwillresignactive: method:

(1) Stop timers and terminate other periodic tasks.

(2) stop any running Metadata Query.

(3) No new tasks are initiated.

(4) pause playing a movie (except for playing on airplay)

(5) The game is suspended.

(6) restore the OpenGL ES frame rate.

(7) suspend any distribution queue or operation queue that is being executed in the critical section. (Of course, when the application is inactive, the application can continue to process network requests and other time-sensitive background tasks)

When the application returns to the active state, it will resume all the work done in the applicationdidbecomeactive: method when the application is suspended. Therefore, when the application is re-activated with reactivate, the application should restart timers, restore any distribution queue, and restore OpenGL ES frame rate. However, the game should not automatically resume operation, and should continue to be paused until the user manually restores them.

When you press the "sleep/wake up" Key, applications with NSFileProtectionComplete protection options that require file protection must disable all references to files. For devices with passwords, lock the screen when you press the "sleep/Wake Up" key and force the system to throw the decryption key to enable full protection. When the screen is locked, any attempt to access the protected file will be fail. So if your application has such protected files, you should disable all references to these files in applicationWillResignActive: method, and in applicationDidBecomeActive: method.

Adjust the UI of your application during the call:

When the user is answering the call and returns to your application to keep the call, the height of the status bar should be increased to reflect the fact that the user is talking. Similarly, when a user finishes a call, the height of the status bar should be reduced to the normal height. The best way to handle Status Bar Height changes is to use view controllers to manage your application views. When the frame size of the status bar changes, view controllers automatically adjusts all internal views managed by them.

If your application does not use view controllers for some reason, you should manually respond to the change in the frame size of the status bar by registering the UIApplicationDidChangeStatusBarFrameNotification notification. The notification handler function handler should obtain the height of the status bar and use the data to moderately adjust the height of the view contained in the current application.

3.3 switch the background status to the test center.

When you press the "Home" key or the system starts another application, the foreground application first switches to the Inactive state and then to the Background state. This conversion will result in successively calling the applicationWillResignActive: And applicationDidEnterBackground: Methods of the application proxy. In applicationDidEnterBackground: After the method is returned, most applications will be transferred to the suincluded status shortly afterwards. Applications that request specific background tasks, such as playing music applications, or those that require additional execution time, may continue to be executed for a longer period of time. The specific process is shown in:

Note: Switching an application from froeground to background only occurs on devices that support multitasking and run iOS4.0 or later versions. In all other cases, the application is terminated directly instead of the backend and cleared from the memory.

What should I do when the application is redirected to the background:

In applicationDidEnterBackground: In the method, make some preparations before the background state is switched to. When the background state is switched to, all applications need to do the following:

(1) Application Interface snapshot. When applicationDidEnterBackground: returns the result, the system saves the snapshot of the application interface and uses the snapshot image as the conversion animation. If you have a view that involves sensitive information in your application interface, you should hide or modify these views before the applicationDidEnterBackground: method returns.

(2) Save User Data and application status information. All unsaved changes should be written to the disk before the background state is switched to save. This step is required because your application may be quickly killed for many other reasons in the background. You can perform these operations in the background thread of the background thread as needed.

(3) release as many memory resources as possible.

Applicationdidenterbackground: The method allows up to five seconds to complete any task and then return it. In practice, this method should be returned as quickly as possible. If this method is not returned after expiration, the application is killed and the occupied memory is cleared. If your application needs more time to execute the task, you can call beginbackgroundtaskwithexpirationhandler to request the background execution time of the method, and then start a thread that can execute the task for a long time. Whether or not you start a thread that executes background tasks, applicationdidenterbackground: The method must exit in 5 seconds.

Note: The uiapplicationdidenterbackgroundnotification notification will also be sent to let the application know the status of the current application tangent to the background. The objects in your application can use the default notification center to register this notification.

Based on different application scenarios, there are many other things to be done when the application is switched to the background. For example, the active bonjour service should be suspended, and the application should stop calling the OpenGL ES function.

Because foreground applications always have a higher priority than background applications when using system resources and hardware. Applications running in the background should be prepared for this difference and adjust their resource access behavior when running in the background. In particular, when the application is switched to the background, the following points must be observed:

(1) do not call any OpenGL ES in application code. When an application is running in the background, it cannot create an eaglcontext object or issue any OpenGL ES painting commands. Using these calls will cause the application to be killed immediately. The application must also ensure that all commands previously submitted and issued have been executed before the application is switched to the background state. For details, see "Implementing a multitasking-aware OpenGL ES application" in "OpenGL ES programming guide for iOS.

(2) cancel all Bonjour-related services before the application suspends the suincluded service. When the application is switched to the background and is suspended, the application should unregister Bonjour service and turn off any sockets listening related to the network service. Pending applications cannot respond to these service requests. If your application does not turn off these Bonjour-related services, the system will automatically turn off these services when the application is suspended.

(3) In network-based sockets applications, you must handle connection failures. When your application is suspended for some reason, the system may remove the socket connection. As long as your application can handle as many network errors as possible, such as losing a signal, such problems will not cause your application to become abnormal. When the application exits from the background and resumes execution, if the sockets usage error occurs, simply re-establish the socket connection.

(4) Save the application status before the background state. When there is a low-memory alarm, background applications may be cleared out of memory to release space. Applications in the sudedded state are preferentially cleared of memory, and no notification is given before being cleared. Therefore, you must save enough application status information before the application enters the background state for future recovery.

(5) When it is switched to the background, all memory that is no longer needed will be released. If your application maintains a large memory cache object (such as image), all references to these cache objects will be released before the background.

(6) Stop using system shared resources before being suspended. Applications that use system shared resources (such as Address Book or Calendar Data) must stop using these shared resources before being suspended. Foreground applications have higher priority to use these resources. If your application has not stopped using these shared resources after being suspended, it should be killed.

(7) avoid updating the application window and view. When an application is in the background, the application window and view are invisible, so you do not need to update it. Although creating and manipulating windows and view objects in the background does not cause the application to be killed, you can postpone the operation until the application returns to the foreground.

(8) respond to external attachment connection and lost connection notifications. For applications that communicate with external attachments, the system sends a disconnection notification when the application switches to the background state. The application must register this notification and use it to disable the access session of the current attachment. When the application returns foreground, a matched notification will be sent, providing the application with the opportunity to re-establish the session.

(9) Clear the resources related to the behavior warning when it is switched to the background. To save the application context between applications, when the application is switched to the backend, the system does not automatically dismiss action sheets (UIActionSheet) and alert views (UIAlertView ). The Application Designer provides a local clearing solution. For applications running before iOS4.0, the action sheet and alerts are still dismiss when exiting, so that the cancellation handler function of the application can be run.

(10) Remove all sensitive view information from the backend. Because the system takes a snapshot of the application interface and generates an application switching animation, the view or window with sensitive information must be hidden or removed.

(11) The minimum amount of work performed by the application in the background. The execution time of applications running on the background by the system is usually very limited compared with that running on the foreground. If the app plays audio in the background or monitors location changes, the app should only focus on this task, and all unnecessary tasks should be postponed. Applications that have been executed in the background for too long will be throttled back by the system or directly killed.

When an application needs to be cleared out of memory due to system memory alarms, the application will call its proxy applicationWillTerminate: Method to execute the last task before the application exits.

Memory usage of background applications:

When an application is switched to the background, each application should release as much memory as possible. The system tries to keep as many applications as possible in the memory at the same time, but when the memory is about to run out, the system will terminate the applications that suspend sudedded to recycle the memory. However, applications that consume a large amount of memory and are running on the background will be terminated first.

To be honest, you need to remove references to used objects as soon as possible when your application no longer needs them. Removing references allows the automatic reference counting system to release objects and reclaim memory. However, if the application uses a cache to improve performance, the application should wait and release the cache before switching to the background status. The following are examples of objects to be recycled:

(1) cached image objects

(2) large multimedia files or data files that can be reloaded from the disk.

(3) Any objects no longer needed by the application, and these objects can be easily re-created later.

To help your applications reduce memory usage, the system automatically releases many objects that are used behind the scenes to support your applications. For example:

(1) release the backup storage of all core animation layers to prevent these layers from being displayed on the screen without changing the attributes of the current layer. The layer object itself is not released.

(2) Remove all references to cached images. (If the application does not have a strong reference to these images, they are subsequently removed from the memory)

(3) release some other data caches managed by the system.

3.4Back to foreground-Modify the submitted Bug

If the application has been moved to the background and the corresponding task is stopped, you can restart the task to continue running when you return to the foreground. ApplicationWillEnterForeground of the application: The method should restore all the work done in applicationDidEnterBackground: method. At the same time, applicationDidBecomeActive: The method should continue to perform the same activation task operations when the application is started. Shows the procedure for an application to switch to the foreground from the background:

Note: If the app registers the UIApplicationWillEnterForegroudNotification notification in the default notification center, the notification is also available when the app re-enters the foreground.

(1) process the notification queue when the application is awakened to the front-end.

Pending applications must always process all notification queues when the foreground or background status is restored. Because the application cannot execute any code when it is suspended, there is no way to deal with those actions or states that affect the appearance of the application, such as direction changes, time changes, preference changes, and others. To ensure that these changes are not lost, the system enters the relevant notifications into the queue and sends them to the application immediately when the application resumes foreground or background re-executes the code. To prevent the application from being overloaded due to too many notifications during restoration, the system will merge events and pass only one single notification that can reflect network changes since the application is suspended.

The following table lists the notification merging rules:

Most notifications are directly delivered to the observers that register them. However, notifications like direction changes are obviously parsed by the system framework, and such notifications are delivered to the application in another way.

The notification queue is typically delivered to the main running loop main run loop of the application before any touch events and user input. Most applications should be able to handle these events quickly enough to avoid any significant lag in application recovery. However, if you find that your application looks stuck when it is recovered from the background, you can use Instruments to determine whether the notification processing code is running, resulting in a delay. When an application returns to the foreground, it also receives update notifications for all views marked as dirty since the update. Applications running in the background can also call setNeedsDisplay or setNeedsDisplayInRect: To request view update. However, because the interface is invisible, the system merges these requests and updates the view only after the application recovers from the foreground.

(2) handle local changes with ease

If the user changes the current language setting, when the application returns to the foreground, you can use the NSCurrentLocalDidChaneNotification notification to force any view containing local sensitive information (such as date, time, number, and so on) to update. Of course, the best way to avoid processing events related to local information is to write the code for updating views in a way that is easier to update views. For example:

A. Use the autoupdatingCurrentLocal class method to retrieve NSLocal objects. This method returns a local object that responds to local changes and automatically updates itself. Therefore, you do not need to recreate it. Then, when the local information changes, your application still needs to refresh the views that contain the local information.

B. Recreate the cache date or Number Format object whenever the local information changes.

(3) Respond to application settings changes

If the application contains the settings managed by the settings application, the application should follow the nsuserdefaultsdidchangenotification notification. When your application is in the background or suspended status, you can modify the settings. Therefore, you can use this notification in your application to respond to any important configuration changes. In some cases, responding to this notification can help turn off some potential security vulnerabilities. For example, the email program should respond to changes in user account information. Failure to monitor these changes may cause privacy and security issues. For example, a user may still use an old user account when sending an email. Even if the account no longer belongs to this user, the user does not think that the new account is used. When the application receives this notification, the application should Reload all the settings-related items and properly reset the user interface, if necessary. For example, when the password or other security-related information is changed, the application should hide any previously displayed information and force the user to enter the new password.

3.5 application termination-end now

Although the application is usually switched to the background or suspended, if any of the following conditions occurs, the application will be terminated and the memory will be cleared:

(1) applications depend on OS versions earlier than ios4.0

(2) the application is deployed on the device running the ios4.0 operating system.

(3) The current device does not support multitasking

(4) The application contains the uiapplicationexitonsuspend key in the info. plist file.

If the application is running on the frontend or backend when it is terminated, the system will call the applicationwillterminate: Method of the application proxy so that the application can be recycled as needed before exiting. You can use this method to save user data or application status information, which can be used when the service is available and then restarted to restore the status. The maximum running time of this method is 5 seconds. Expired applications are killed and the memory is removed.

Note: The applicationwillterminate: method is not called when the application is sudedded.

Even if you use IOS sdk4 or an updated version of the SDK to develop an application, you should also consider the situation where the application is killed without notice. You can use the multitasking UI to clearly kill an application. In addition, if a memory alarm occurs, the system also removes the application from the memory to release the space. No notification will be sent when an application in the sudedded state is terminated. However, if the application is currently running in the background, the system will call the applicationwillterminate method of the application proxy when the application is to be terminated. The application cannot apply for additional background execution time in this method.

3.6 main run loop-boring coding stage

The main running cycle of the application is responsible for handling all user-related events. When the application starts, the uiapplication object installs the main running cycle and uses this cycle to process events and view-based interface updates. As indicated by the name, the main running cycle runs in the application's main thread app's main thread. This ensures that all user events are executed sequentially according to the order in which they are received.

Demonstrate the structure of the main running cycle and how user events lead to application behavior. When a user interacts with an application, events related to the interaction are automatically generated by the system and passed to the application through the special ports set by uikit. Events exist in the application in the form of queues and are distributed one by one to the main running cycle of the application for execution. The uiapplication object is the first object to receive events and determines how to handle events. A touch event is usually distributed to the application's main window object and finally distributed to the view where the touch event occurs. The transfer of other events may pass through a variety of application objects, which is slightly different from the transfer of touch events.

Many types of events can be passed in IOS apps. The most common events are listed in the following table:

Most of these event types are passed through the main running loop of the application, but some are not. For example, the accelerometer event is directly transmitted to the accelerometer proxy image specified by the application. For details about how the system handles most types of events, including touch, remote control, motion, accelerometer, and gyroscopic events, see event handling guide for IOS.

Events such as touch and remote control are usually processed by application response objects. The response object exists anywhere in the application. (The UIApplication object, view object, and view controller object are examples of response objects ). Most events are targeted at specific response objects, but can also be passed to other response objects (with the help of the response chain), such: A view that does not process any event can pass the event to its parent view or view controller.

The processing process of events that occur on a view (such as a button) of the controls class is somewhat different from that of touch events that occur on other types of views. Because there are only a few interactions on control objects, these interactions are repackaged into active messages and passed to the appropriate target object. This target-action design mode makes it easy for an application to trigger execution of a custom code by using a view object of the control type.

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.