2016-06-15 2 views
0

그래프 라이브러리를 사용하고 Swift 프로젝트의 UIWebview에 웹 페이지를로드했습니다.Swift에서 Javascript 값 업데이트하기

Swift UIViewController에서 HTML 파일 그래프 Y 축 값을 업데이트 할 수 있습니까?

가능한 경우 제게 제안 해주세요.

자세한 정보는 아래 코드와 스냅을 참조하십시오.

는 Startup.html

<!DOCTYPE HTML> 
<html> 

<head> 
    <script type="text/javascript"> 
     window.onload = function() { 
      // initial values of dataPoints 
      var dps = [ 
         {label: "Management Wing", y: 125} , 
         {label: "Production Lab", y: 332}, 
         {label: "Cafeteria", y: 55}, 
         {label: "Library", y: 46}, 
         {label: "Recreation Centre", y: 32} 
         ]; 

         alert(dps.y); 

         var totalEmployees = "Total people on campus: 590"; 

         var chart = new CanvasJS.Chart("chartContainer",{ 
                 theme: "theme2", 
                 title:{ 
                 text: "People On Campus" 
                 }, 
                 axisY: { 
                 title: "Number of People" 
                 }, 
                 legend:{ 
                 verticalAlign: "top", 
                 horizontalAlign: "centre", 
                 fontSize: 18 

                 }, 
                 data : [{ 
                   type: "column", 
                   showInLegend: true, 
                   legendMarkerType: "none",    
                   legendText: totalEmployees, 
                   indexLabel: "{y}", 
                   dataPoints: dps 
                   }] 
                 }); 

                 // renders initial chart 
                 chart.render(); 

                 var sum = 590;  //initial sum 

                 var updateInterval = 1000; // milliseconds 

                 var updateChart = function() { 
                  // Selecting a random dataPoint 
                  var dataPointIndex = Math.round(Math.random()*4);  

                  // generating random value 
                  var deltaY = Math.round(2 + Math.random() *(-2-2)); 

                  // adding random value to random dataPoint 
                  dps[dataPointIndex].y = (dps[dataPointIndex].y + deltaY) > 0 ? dps[dataPointIndex].y + deltaY : 0 ; 

                  // updating legend text. 
                  sum = sum + deltaY; 
                  totalEmployees = "total people on campus: " + sum;    
                  chart.options.data[0].legendText = totalEmployees;  

                  chart.render(); 

                 }; 
                 // update chart after specified interval 
                 setInterval(function(){updateChart()}, updateInterval); 

     } 
    </script> 

    <script type="text/javascript" src="/Users/wipro/Shiv_Suthan_M_Drive/Suthan_Drive/Apple_Dev/Projects/Swift/SwiftScript/SwiftScript/canvasjs.min.js"></script> 
</head> 
<body> 
    <div id="chartContainer" style="height:300px; width:100%;"> 
    </div> 
</body> 

Viewcontroller.Swift는

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    let localfilePath = NSBundle.mainBundle().URLForResource("startup", withExtension: "html") 
    let myRequest = NSURLRequest(URL: localfilePath!); 
    modelWebView.loadRequest(myRequest); 

    /* 
    let url = NSURL (string: "https://www.sourcefreeze.com"); 
    let requestObj = NSURLRequest(URL: url!); 
    modelWebView.loadRequest(requestObj); 
    */ 


} 

Screen Shot

그래서 것은 내가 upda 원하는됩니다 Swift의 자바 스크립트 데이터 포인트 (Y 축)를 테.

+0

웹보기에 대한 설명서를보십시오. – Wain

+0

html을 문자열로 사용하고 있습니까? –

+0

@Nirav 아래 코드를 사용하면 HTML 문자열이 제대로 작동합니다. { myHTMLString = tryString (contentsOfURL : localfilePath!) print ("HTML : \ (myHTMLString)") } NSError { print ("Error : \ (error)") }하지만 어떻게 데이터 포인트를 변경하고 JS로 되돌릴 수 있습니까? –

답변

1

업데이트 HTML 파일과 같은

var dps = [ 
    {label: "Management Wing", y: %ld}, 
    {label: "Production Lab", y: %ld}, 
    {label: "Cafeteria", y: %ld}, 
    {label: "Library", y: %ld}, 
    {label: "Recreation Centre", y: %ld} 
]; 

이하 이제 코드를 다음과 같이 변경하십시오.

let localfilePath = NSBundle.mainBundle().URLForResource("demo", withExtension: "html") 
do { 
    var myHTMLString = try NSString(contentsOfURL: localfilePath!, encoding: NSUTF8StringEncoding) 
    myHTMLString = NSString(format: myHTMLString, 123, 25, 100, 46, 85) // Add 5 number that you want to change 
    webView.loadHTMLString(myHTMLString as String, baseURL: NSBundle.mainBundle().URLForResource("", withExtension: "")) //Add your js file here 
} 
catch let error as NSError 
{ 
    print("Error: \(error.description)") 
} 

희망이 도움이 될 것입니다.

+0

내가 위에서 시도한 동안 webview에서 그래프를 찾을 수 없다. 나는 JS로 업데이트되지 않은 값을 추측한다. ?? :(그 밖의 다른 것은 yurs의 유일한 두 가지 방법을 설치해야합니까? –

+0

html로 숫자 대신 % ld를 넣었습니까? –

+0

내 대답 검사를 편집했습니다. 프로젝트에 Java 스크립트 파일을 추가해야합니다. 그 파일을 loadHTMLString의 NSBundle에 넣으십시오. –

0

예 jscript를 사용하여 매개 변수를 전달하고 UIWebview에서 값을 업데이트 할 수 있습니다.

다음은 유용한 링크입니다. 이것을 시도하고 적절한 논리를 적용하십시오. 그것은 나를 만든 일이다. (이 링크는 목표 다입니다 그러나 그것은 또한 당신에게 적절한 논리를 적용 SWIFT의 일이다)

JavascriptCore: pass javascript function as parameter in JSExport

Pass variables from Objective-C to javascript function?

How to invoke Objective C method from Javascript and send back data to Javascript in iOS?

관련 문제