【问题标题】:Nativescript accessing localhost access in android and iosNativescript 在 android 和 ios 中访问 localhost 访问
【发布时间】:2016-08-23 17:51:35
【问题描述】:

我的系统上运行了一个本地节点 rest api。

我的问题是,当从 android 访问 localhost 时,我们应该使用 10.0.2.2。使用 ios 时,我们可以使用 localhost 。

那么有没有一种方法可以控制我们调用的主机名,这取决于原生脚本应用程序中的 ios 或 android 环境

【问题讨论】:

    标签: android ios nativescript angular2-nativescript


    【解决方案1】:

    您可以在 JS 文件中使用以下内容(当您需要快速决定每个平台代码使用什么时更好)

    /*at top file*/
    var platform = require("platform");
    var nativePlatformLocalhost;
    
    /*in some function or globally*/
    if(platform.device.os === platform.platformNames.ios){
      /*localhost for ios*/
      nativePlatformLocalhost= "localhost";
    }
    else if(platform.device.os === platform.platformNames.android){
      /*localhost for android*/
      nativePlatformLocalhost= "10.0.2.2";
    }
    

    或者如果您需要基于平台的更复杂的 android / ios 代码,您可以编写两个文件,一个用于 android,一个用于 ios,具有名称约定,并要求如下行

    require("file.js");
    

    当您创建两个具有以下名称的文件时,您将获得基于当前运行平台运行时的文件

    file.android.js 
    file.ios.js
    

    http://docs.nativescript.org/ui/supporting-multiple-screens.html#platform-qualifiers

    【讨论】:

      【解决方案2】:

      添加答案的打字稿版本

      import {platformNames} from "platform";
      import {device} from "platform";
      
        var nativePlatformLocalhost;
      
           /*in some function or globally*/
          if(device.os === platformNames.ios){
           /*localhost for ios*/
           nativePlatformLocalhost= "localhost";
         }
        else if(device.os === platformNames.android){
          /*localhost for android*/
          nativePlatformLocalhost= "10.0.2.2";
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-11
        • 2017-11-12
        • 2015-11-22
        • 2017-07-26
        • 2016-02-29
        • 1970-01-01
        • 2016-09-11
        • 2020-11-15
        相关资源
        最近更新 更多