This sharing is mainly divided into two parts:

  • Some introduction of iOS development knowledge, so that people can have a direction to search for relevant information when they come into contact with RN/Flutter project but do not have mobile colleagues;
  • The iOS side and the Web side call each other and debug some generalizations.

As the sharing process will be interspersed with Xcode demonstrations and oral explanations, the article only provides a partial list of key information

System hierarchy architecture diagram

There are four main levels: Cocoa Touch, Media, Core Service and Core OS.

  • As its name implies, the Cocoa Touch Touch UI layer contains many frameworks related to user interaction, which are key frameworks for developing iOS apps. It provides the infrastructure of the App, as well as system services such as touch, push, multi-tasking and push.

    UIKit is the most commonly used for interface construction.

  • The Media layer provides the processing ability for App to process various Media files, such as audio and video codec, graphic drawing, animation effect and so on.

  • The Core Services layer contains the basic system Services used by all apps. Even if you don’t use these services directly, many parts of your system are built on top of them.

    Among them, Foundation is the most commonly used. It provides basic functions for upper-layer frameworks and App development, as well as basic data types and operation tools, such as collection type processing, string processing, date processing, file processing, exception handling, etc.

  • The Core OS layer contains the underlying functionality on which most other technologies are based. Responsible for memory management, file system tasks, network processing, and other operating system tasks, as well as interacting directly with hardware devices. In general, most development situations don’t use this layer directly; the upper framework uses them.

IOS Technology Overview -TP40007898 7.0.3-

Basic knowledge overview

Engineering documents

Since most Web developers encounter iOS projects that are automatically created when react-native /Flutter/Weex is initialized, let’s take a look at the project files:

  • *.h: header file that declares classes, methods, and properties and exposes the accessible interface.
  • *.m:.hTo add private methods and attributes.
  • *.pch: precompiled header file, usually used for placementMacro definitionPublic header file





  • *.xib: Visual View layout file, the essence is to useXMLDescribes the View layout file
  • *.storyboard: Storyboard,xibThe enhanced version is also usedXMLDescribes the layout file, but can be placed, connected to control multiple page jump logic
  • *.plistFull name:Property ListProperty list, which can be used to store the sequenceAfter the column ofObject commonly used for storageUser configuration, lightweight persistence solution
  • *.lproj: internationalization package, which can be includedThe text,The picture,xib,storyboard
  • *.xcassets: (image) Resource file package, usually used for placementImage resourcesAnd then increasedcolorEtc.





  • Podfile: widely used package dependency management (Cocoapods), analogous to a Web projectpackage.json
  • *Podfile.lockThe dependency management tool installs a locked version of a dependency, analogous to a Web projectpackage-lock.json





  • *. Xcodeproj: Xcode project file that stores the various configurations of the project
  • *.xcworkspace: Xcode project files, usually using dependency management toolsCocoapodsperformpod installAfter the installation of a dependency generated (can also do their own, is multiplexcodeprojA collection of.

Design patterns

The bare explanation is not well understood either, so take a look at the design pattern example project.

But there are a few things that I want to talk about so that I can understand them

What are the prefixes like NS, UI, AV, CF?

Since there is no concept of namespaces in OC, we use prefixes to avoid conflicts. Developers usually use uppercase letters of their names/company abbreviations as prefixes. Apple reserves the right to use all 2 letters as prefixes. NS stands for NeXTSTEP, a system developed by NeXT.Inc., founded by Steve Jobs, with its native support for Objective-C. NeXT was acquired by Apple in 1997 and became the basis of Mac OS. Other examples include UI -> UIKit, AV -> AVFoundation/AVKit (Audio+Video), CF -> CoreFoundation

What is @?

First, the keyword is preceded by @, such as: @class, @interface, @implementation, @end, @protocol, etc. The second is used as syntax sugar, such as string @””, number @(1) @(YES) @(0.0), array @[], dictionary @{}, etc

demo

See the example project for details. This section is mainly explained in the sharing and is not reflected in the article


Let’s talk about iOS and Web side development coordination.

WebView interacts with Native

There are two kinds of WebViews in iOS, UIWebView and WKWebView:

  • UIWebView (iOS 2.0 ~ 12.0) runs in the App process. The memory for loading the page is counted as the memory occupied by the App. When the App memory exceeds the limit, the App will be notified to process it. New apps will be banned from April 2020, and all App updates will be banned by the end of the year.

  • WKWebView (iOS 8.0 ~) is an independent process. When its memory usage exceeds the memory allocated by the system to WKWebView, the WKWebView will crash and notify the app to process the process. The app will not be killed if the process is not processed. It has 1/3 to 1/4 of the memory of UIWebView, so it starts faster. Asynchronously handles JS that communicate with native Bridges.


  • Although it has been supported since iOS 8.0, there are a lot of issues, so it is generally used from 9.0. However, given the high rate of iOS updates (50% of iphones are iOS 13 and 41% are iOS12, according to official data so far), this is largely negligible.
  • Cookies are not portable.
  • The body of a POST request made by a loadRequest is discarded.
  • Requests cannot be intercepted using NSURLProtocol directly.

This is the main encounter, more other can refer to bugly WKWebView those pits

URL interception, commonly used Scheme

Similar to the mhc://b.maihaoche.com? Type = xxx&value = XXX

<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
            // Define the method executed by Native calls
            function showAlert(message){
                alert(message);
            }
            // Open a url-scheme by initiating iframe
            function loadURL(url) {
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", url);
                iFrame.setAttribute("style"."display:none;");
                iFrame.setAttribute("height"."0px");
                iFrame.setAttribute("width"."0px");
                iFrame.setAttribute("frameborder"."0");
                document.body.appendChild(iFrame);
                // This iFrame is useless after the request is made, so remove it from the DOM
                iFrame.parentNode.removeChild(iFrame);
                iFrame = null;
            }
            // Click the HTML button
            function firstClick() {
                loadURL("mhc://b.maihaoche.com?type=xxx&value=xxx");
            }
        </script>
    </header>

    <body>
        <h2> scheme </h2>
        <button type="button" onclick="firstClick()">Click Me!</button>
    </body>
</html>
Copy the code

Universal Links

For server configuration, see iOS9 Universal Links pothole tour and deeplink wake-up app

JavaScriptCore

UIWebView only available

  • The web client implementation
<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function secondClick(a) {
            // Call native defined methods
            nativeShare('Shared title'.'Shared Content'.'Picture address');
        }
        </script>
    </header>

    <body>
        <h2> JSCore </h2>
        <button type="button" onclick="secondClick()">Click Me!</button>
    </body>
</html>
Copy the code
  • The iOS side implementation
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // The native method exposed to the Web call, nativeShare
    context[@"nativeShare"] = ^ () {NSArray *args = [JSContext currentArguments];
        for (JSValue *val in args) {
            NSLog(val.toString); }}; }Copy the code

WKWebView

  • The Web client implementation
function btnClick() {
    // window.webkit.messageHandlers. Method name. PostMessage;
    window.webkit.messageHandlers.nativeShare.postMessage('params');
}
Copy the code
  • The iOS side implementation
// Listen for web methods
- (void)setupScriptHandler{
    [self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"nativeShare"];
}

// Perform a Web call to native
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"nativeShare"]) {
        // The parameters passed from the web
        NSLog(message.body);
        
        // objc executes the web method
        [self.wkWebView evaluateJavaScript:@"alert(\" Share success \")" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            // web callback}]; }}Copy the code

WebViewJavascriptBridge

Erase the difference between UIWebView and WKWebView WebViewJavascriptBridge

Debug webView on mobile

Using the mobile view mode only on the PC side sometimes cannot guarantee the consistent performance in the browser /App on the mobile side, so how to debug?

The preparatory work

Simple Settings for Safari on Mac/iOS are required

  • Mac Safari

  • iOS Safari

Start debugging

Debugging can be done in Safari or in an App, but in either case you need to connect your phone to your computer first. (Wireless connectivity depends on the complexity of your LAN, and sometimes it’s not possible at home, but not at work.)

Web page opened in Safari

For example, if you open www.baidu.com in Safari on mobile, you’ll see Safari- Development – Mobile – on Mac with the following options

When you open it, you will see the following image that pops up a common Web inspector tool. I believe you are more familiar with most of the operation points than I am. Here are a few tips:

  1. Click on the tool in the red box (the blue sight) and click on the Web element directly on the phone to trigger the selection
  2. When you hover over a Web element (such as the code in the green box), you can see the corresponding element box identifier on the phone
  3. The selected Web element/code/executed code, as follows= $* (* = 0, 1, 2.....)You can use it directly from the console

The Web page opened in the App

First of all, you need to make sure that the App on your phone is directly Debug Run by the developer using Xcode (scanning distribution download is not supported), or the simulator can use the package dragged in (but remember to check whether the simulator’s Safari web page inspector is open).

Use web embedding tools

Web developers can also embed a development tool directly into a Web project, such as:

  • vConsole

  • eruda

Some information

human-interface-guidelines

WWDC-Videos

iOS Programming Tricks

Js-native interactive ebook. PDF

Websites for iPhoneX

DarkMode in Webkit