运行JS代码以获取swift中的数据

时间:2017-02-13 10:26:35

标签: javascript ios swift javascriptcore

我需要在CloudKit中获取CkAsset的网址。但是,在swift中,Apple不允许我们获取直接的WebURL,它只下载资产并向我们提供fileURL。但是,使用javascript是可能的。因此,我写了一个获取CkAsset WebURL的JS文件。当我在浏览器中运行此javascript文件时。我试图用下面的代码快速运行它,但我不能。当我搜索时,有一个名为“stringByEvaluatingJavaScriptFromString”的函数,但我无法弄清楚如何运行它。

的index.html

        <meta charset="utf-8">
  <title>TIL - Today I Learned</title>
  <script src="https://cdn.apple-cloudkit.com/ck/1/cloudkit.js" async></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
  <script type="text/javascript" src="TIL.js"></script>

javascript文件:

window.addEventListener('cloudkitloaded', function() {
  console.log("listening for cloudkitloaded");
  CloudKit.configure({
    containers: [{
      // To use your own container, replace containerIdentifier and apiToken
      containerIdentifier: 'iCloud.com.emreonder.ogun-dalka-music',
      apiToken: '42ba168168dbf3a8c9562904ebf311864258f8dd3638a241d2372057ea0e8a55',
      environment: 'development'
    }]
  });
  console.log("cloudkitloaded");

    var self = this;
    console.log("get default container");
    var container = CloudKit.getDefaultContainer();

    console.log("set publicDB");
    var publicDB = container.publicCloudDatabase;
    self.items = ko.observableArray();

    // Fetch public records
  //  self.fetchRecords = function() {
      console.log("fetching records from " + publicDB);
      var query = { recordType: 'Musics'};

      // Execute the query.
      return publicDB.performQuery(query).then(function(response) {
        if(response.hasErrors) {
          console.error(response.errors[0]);
          return;
        }
        var records = response.records;
        var numberOfRecords = records.length;
        if (numberOfRecords === 0) {
          console.error('No matching items');
          return;
        }

        console.log(records.length + " records")
        console.log(records);
        self.items(records);
      });
  //  };
});

Swift文件:

 let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let myRequest = NSURLRequest(url: url!);
    webView.loadRequest(myRequest as URLRequest);
    print(webView.pageCount)
    let test_string = webView.stringByEvaluatingJavaScript(from: "function();")
    print(test_string)
编辑:我也把html文件,但现在我不知道如何调用javascript函数。

1 个答案:

答案 0 :(得分:0)

经过努力尝试后,我才知道。我想解决我的问题。通过此解决方案,您可以在CloudKit上获取流URL(例如资产)。

首先我创建了一个webView(实际上,它只是在代码中,GUI中没有任何内容)。

  let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let myRequest = NSURLRequest(url: url!);
    webView.loadRequest(myRequest as URLRequest);
    webView.delegate = self

然后我通过stringByEvaluatingJavaScript函数获取我的js文件中的变量(我需要在js文件中的函数下面创建一个变量

 let a = webView.stringByEvaluatingJavaScript(from: "myVar")
    print(a!)
    let url : NSString = a! as NSString
    let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString
    let searchURL : NSURL = NSURL(string: urlStr as String)!
    print(searchURL)
    /*https://cvws.icloud-content.com/B/AVHgxc_-X3u9H5xK684KmUQrzDqp/$%7Bf%7D?o=Apgif1Giyg-lwRiNre2KJYl-5EhUAiL1m1OgE3-osxpxexWD7YGjCAOFCoQLRv8sGUglywu2tGr-OgfGtDZ15k0&v=1&x=3&a=BbLB0UptOX3bA-k6OQ&e=1487341935&k=_&fl=&r=0f83571c-d168-4743-b38b-0e808baa0a1a-1&ckc=iCloud.com.emreonder.ogun-dalka-music&ckz=_defaultZone&p=61&s=OuE127GKlo_0EIZ6y5t49gMv0qM 
     */
    let playerItem = AVPlayerItem(url: searchURL as URL)
    player = AVPlayer(playerItem: playerItem)
    let playerLayer:AVPlayerLayer = AVPlayerLayer(player: player)
    self.view.layer.addSublayer(playerLayer)
    self.player.play()