顯示具有 iOS 標籤的文章。 顯示所有文章
顯示具有 iOS 標籤的文章。 顯示所有文章

2018年2月13日 星期二

將React Native0.53與現有的iOS整合

版本

  • xcode 9.2(9C40b)
  • react-native 0.53.0
  • react 16.0.0-beta.5

參考

前言

這版本在與原專案集成的坑真的不是普通的多...希望下一版能全部修復

步驟

  1. 新建一個iOS single view app,如果已經有iOS專案,可以跳到第三步

  2. 初始化pod

    > pod init
    
  3. 新增一個資料夾,然後在裡面新建一個ios資料夾,把iOS專案拉進來,這時目錄應該是這樣

    - RNFloder
        - ios
            - iosProjectName
                - ...
                - Assets.xcassets
                - ...
            - iosProjectName.xcodeproj
            - iosProjectName.xcworkspace
            - ... 
    
  4. 在React Native根目錄初始化npm,npm是js的CocoaPods,一般只要一直按enter就好了,他會在你的目錄下多出一個package.json檔案,作用等同於Podfile

    > npm init
    
  5. 接著安裝React Native相關的js lib,根據官方文件,必須要以下react版本,因為rn對react版本很敏感

    > npm install --save react@16.0.0-beta.5 react-native
    
  6. 在Podfile中將React Native lib引入到專案

    target 'ReactNativeiOSHybrid' do
              use_frameworks!
      # 'node_modules'目錄一般位於根目錄中
      # 但是如果你的結構不同,那你就要根據實際路徑修改下面的`:path`
      pod 'React', :path => '../node_modules/react-native', :subspecs => [
        'Core',
        'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
        'RCTText',
        'RCTNetwork',
        'RCTWebSocket', # needed for debugging
        'CxxBridge',
        # Add any other subspecs you want to use in your project
      ]
      # Explicitly include Yoga if you are using RN >= 0.42.0
      pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
    
      # Third party deps podspec link
      pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
      pod 'GLog', :podspec => '../node_modules/react-native/third-party-podspecs/GLog.podspec'
      pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
    
    end
    
    # 這裡要注意,如果CocoaPods在install的時候出了問題,記得下pod cache clean --all,不然會有緩存導致之後改動Podfile還是會install失敗
    
  7. CD到React Native目錄下的iOS目錄,安裝相關iOS lib

    > pod install
    
  8. 啟動Xcode,run app

  9. 這時候會發現有錯誤

    Yoga-internal.h:11:10 : fatal error: 'algorithm' file not found: #include 
    
  10. 這是因為react native(或是yoga?反正都是facebook)官方podspec沒配置好

  11. 接著按照github有一個還沒過的PR改動,打開以下文件

    > cd RNProject/node_modules/react-native/ReactCommon/yoga
    > vim yoga.podspec
    
  12. 在最後面補上

        ...
        ...
      # Set this environment variable when not using the `:path` option to install the pod.
      # E.g. when publishing this spec to a spec repo.
      source_files = 'yoga/**/*.{cpp,h}'
      source_files = File.join('ReactCommon/yoga', source_files) if ENV['INSTALL_YOGA_WITHOUT_PATH_OPTION']
      spec.source_files = source_files
    
      # 補上以下兩句
      spec.public_header_files = 'yoga/Yoga.h', 'yoga/YGEnums.h', 'yoga/YGMacros.h'
    
    end
    
  13. 這樣就解決了algorithm.h找不到的問題,問題解決,想了解更多可以看一下這個issue:React Native iOS Pod issues: fatal error: 'algorithm' file not found

  14. 接著運行,還會報一個fishhook/fishhook.h頭文件找不到的問題

  15. 找到該報錯文件,將報錯的import改成以下

    #import fishhook/fishhook.h -> #import fishhook.h
    
  16. 問題解決,想了解更多可以看一下這個issue:React Native iOS issues: Fishhook error

  17. 然後在React Native根目錄新增一個index.js文件,這個是用來測試的React Native頁面

    import React from 'react';
    import { AppRegistry, StyleSheet, Text, View } from 'react-native';
    
    class RNHighScores extends React.Component {
      render() {
        var contents = this.props['scores'].map((score) => (
          <Text key={score.name}>
            {score.name}:{score.value}
            {'\n'}
          </Text>
        ));
        return (
          <View style={styles.container}>
            <Text style={styles.highScoresTitle}>2048 High Scores!</Text>
            <Text style={styles.scores}>{contents}</Text>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFFFFF',
      },
      highScoresTitle: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      scores: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
    });
    
    // Module name
    AppRegistry.registerComponent('RNHighScores', () => RNHighScores);
    
  18. 然後在React Native根目錄執行以下指令,他會在local端開啟一個server,供React Native讀取我們開發中的Reat Native文件,他會自動打包成bundle

    > npm start 
    
  19. 然後執行Xcode->run iOS專案,或是在根目錄

    > react-native run-ios
    
  20. 如果你使用的是0.53.0版的React Native,你會出現以下錯誤

    No component found for view with name "RCTText"
    
  21. 這是由於我們facebook工程師一個美妙的錯誤,詳情可以看以下issue:React Native iOS issue: No component found for view with name "RCTText"

  22. 依照以上issue的解決方案,打開./node_modules/react-native/React.podspec

      s.subspec "RCTText" do |ss|
        ss.dependency             "React/Core"
    -   ss.source_files         = "Libraries/Text/*.{h,m}"
    +   ss.source_files         = "Libraries/Text/**/*.{h,m}"
      end
    
  23. 在iOS目錄下重新 pod install

  24. OK,畫面出現,歷經了千辛萬苦,終於可以愉快地使用React Native了


author Iml1s

email ImL1s@outlook.com

若我的文章有幫助到你,可以考慮請我喝杯咖啡:D

2018年2月8日 星期四

React Native CodePush集成

author: ImL1s

email: ImL1s@outlook.com

github: 專案

參考

版本

  • react-native-cli: 2.0.1
  • react-native: 0.53.0
  • code-push: 2.1.6

前置作業

註冊CodePush

  1. 安裝CodePush CLI

    > npm install -g code-push-cli
    > code-push -v
    2.1.6 // 有顯示版本號代表安裝成功
    
  2. 向CodePush註冊App

    > code-push app add CodePushIntergradation ios react-native
    ┌────────────┬──────────────────────────────────────────────────────────────────┐
    │ Name       │ Deployment Key                                                   │
    ├────────────┼──────────────────────────────────────────────────────────────────┤
    │ Production │ xxxxs2KwnRds65xxxxbp2GpYF78h3bxxxx1f-xxxx-xxxx-bba3-5a79beaxxxxd │
    ├────────────┼──────────────────────────────────────────────────────────────────┤
    │ Staging    │ xxxxgs9s-QBRsxxxxGxxxxGGxxhxxxx467xf-xxx3-430a-bba3-5a7xxxx95xxx │
    └────────────┴──────────────────────────────────────────────────────────────────┘
    

公有雲的CodePush集成到新的iOS專案(OC)

  1. 新建一個React Native專案

    react-native init codePushIntergradation
    
  2. 在新建的React Native目錄下,使用npm安裝CodePush

    npm install --save react-native-code-push
    
  3. 再run一次安裝

    npm install
    
  4. 執行以下指令,會打開瀏覽器訪問M$的app center,按照步驟登入或是註冊

    > code-push register
    
  5. 上面的步驟完畢,在瀏覽器中可以得到一串金鑰

    fxxxdd9caxxxxxxadxxxc3xxxc9904xxxd5xxx1x
    
  6. 將金鑰輸入到終端機中,他會將session文件存在~/.code-push.config

    Successfully logged-in. 
    Your session file was written to /Users/userName/.code-push.config. 
    You can run the code-push logout command at any time to delete this file and terminate your session.
    
  7. 接著輸入以下指令,證明你已經登入了

    > code-push login
    [Error]  You are already logged in from this machine.
    
  8. 接著安裝幫原生的iOS/Android專案安裝CodePush的lib,deployment key先不用輸入,按Enter就好

    > react-native link react-native-code-push
    
    Scanning folders for symlinks in /Users/UserName/Project/IOS/CodePushIntergradation/node_modules (18ms)
    ? What is your CodePush deployment key for Android (hit <ENTER> to ignore) 
    rnpm-install info Linking react-native-code-push android dependency 
    rnpm-install info Android module react-native-code-push has been successfully linked 
    rnpm-install info Linking react-native-code-push ios dependency 
    rnpm-install info iOS module react-native-code-push has been successfully linked 
    Running ios postlink script
    ? What is your CodePush deployment key for iOS (hit <ENTER> to ignore) 
    Running android postlink script
    
  9. 在iOS專案中,使用Source Code方式打開info.plist,在裡面新增or更改CodePushDeploymentKey這個key的值為向CodePush註冊的Staging key(在上面前置作業申請的)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        ...
        ...
        <key>CodePushDeploymentKey</key>
        <string>iGexxx9s-Qxxx1xxxGkxxxGxxxhF3xxx67xx-xxxx-43xx-xxxx-xxxxxxx9xxxd</string>
    </dict>
    </plist>
    
  10. 接著打開AppDelegate.m,可以看到以下程式碼,cli工具已經幫我們把RCTRootView(React Native JS的運行容器)更新的Code都寫好了

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        ...
        ...
        #ifdef DEBUG
            jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
        #else
            jsCodeLocation = [CodePush bundleURL];
        #endif
        RCTRootView *rootView = 
        [[RCTRootView alloc] 
        initWithBundleURL:jsCodeLocation
            moduleName:@"codePushIntergradation"
            initialProperties:nil
            launchOptions:launchOptions];
       ...
       ...
    }
    
  11. 接著我們還要設定iOS的http訪問權限,打開info.plist,把CodePush的Url加入進去

    <plist version="1.0">
      <dict>
        <!-- ...other configs... -->
    
        <key>NSAppTransportSecurity</key>
        <dict>
          <key>NSExceptionDomains</key>
          <dict>
            <key>codepush.azurewebsites.net</key>
            <dict><!-- read the ATS Apple Docs for available options --></dict>
          </dict>
        </dict>
    
        <!-- ...other configs... -->
      </dict>
    </plist>
    
  12. 將React Native的index.js改成以下

    import { AppRegistry } from 'react-native';
    import App from './App';
    
    import codePush from "react-native-code-push";
    
    AppRegistry.registerComponent('codePushIntergradation', () => codePush(App));
    
  13. 接著用Release模式Run,一定要Release喔,不然他只會讀local的js

  14. xcode怎麼找到最新的React Native js的呢?因為Xcode裡,react-native cli工具幫我們配置了一個run script,可以切到以下地方,找到一個.sh的script,這個script會在Copy Bundle Resources之後將打包好的js放到ipa中(可以參考開頭參考的連結)

    點擊項目 -> TARGETS -> {{porject name}} -> BuildPhases ->Bundle React Native code and images
    
  15. 接著修改React Native的app.js

    export default class App extends Component<Props> {
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
             Hello code push!!
            </Text>
            <Text style={styles.instructions}>
              To get started, edit App.js
            </Text>
            <Text style={styles.instructions}>
              {instructions}
            </Text>
          </View>
        );
      }
    }
    
  16. 接著要把React Native專案下的package.json版本號更新,不然不給上傳

    {
      "name": "codePushIntergradation",
      "version": "0.0.2",
      "private": true,
      "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
      },
      "dependencies": {
        "react": "16.2.0",
        "react-native": "0.53.0",
        "react-native-code-push": "^5.2.1"
      },
      "devDependencies": {
        "babel-jest": "22.2.0",
        "babel-preset-react-native": "4.0.0",
        "jest": "22.2.1",
        "react-test-renderer": "16.2.0"
      },
      "jest": {
        "preset": "react-native"
      }
    }
    
  17. 接著將寫好的js打包,並且發布到遠端Server上,這句command做兩個動作,打包React Native專案並且上傳到Code push

    > code-push release-react {{Your project name}} ios 
    
  18. 重新打開app兩次(滑掉重開),然後可就可以看到更新,至於為什麼要兩次呢...?我猜是為了用戶體驗,第一次檢查到更新先存著,等到下一次再更新

常用指令

初始化階段:
1:npm install -g code-push-cli 安裝客戶端
2:code-push -v 查看是否安裝成功
3:code-push register 在codepush注冊賬號
4:code-push login
5:code-push app add <appName> <android/ios> react-native 添加app
例如
code-push app add test android react-native

6:code-push app list 列出app列表
code-push deployment ls <appName> -k 查看APP的key
code-push deployment history <appName> Porduction/Staging
例如:
code-push deployment history test Production

7:yarn add react-native-code-push 在rn項目下安裝codepush
8:react-native link react-native-code-push 鏈接codepush