0

I used some graph library and load the web pages into the UIWebview in my Swift project.

Is it possible to update the HTML file graph Y axis value from Swift UIViewController.

If it's possible, please suggest me some example.

More info please find the code and snap below.

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

So thing is I want to update the javascript datapoints (Y axis) from Swift .

Eiko
  • 25,601
  • 15
  • 56
  • 71
Suthan M
  • 443
  • 8
  • 21
  • Look at the documentation for the web view. – Wain Jun 15 '16 at 06:41
  • You have html as a string? – Nirav D Jun 15 '16 at 06:46
  • @Nirav I'm using below code to retrive the HTML string its working fine do { let myHTMLString = try String(contentsOfURL: localfilePath!) print("HTML : \(myHTMLString)") } catch let error as NSError { print("Error: \(error)") } But How can i change the datapoints and revert to JS ? – Suthan M Jun 15 '16 at 06:51
  • Have you try my answer? Fill free to ask question. – Nirav D Jun 15 '16 at 07:21

2 Answers2

1

Update your html file like below

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}
];

Now change your code like this

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)")
}

Hope this will help you.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • While i tried above I can't find the Graph in the webview, I guess the values not updated to JS ?? :( Anything else do i need to setup else the only two methods of yurs ?? – Suthan M Jun 15 '16 at 07:23
  • have you put %ld instead of number in html? – Nirav D Jun 15 '16 at 07:27
  • I have edited my answer check that. You need to add the java script file in your project and give that file in the NSBundle in loadHTMLString – Nirav D Jun 15 '16 at 07:33
  • I'm not handling any separate JS file, I'm using HTML inside of JS function alone.. @Nirav Pls find the coding part of mine above. – Suthan M Jun 15 '16 at 07:44
  • I am talking about this `canvasjs.min.js` file – Nirav D Jun 15 '16 at 08:36
  • The code was working fine. But the values got changed continuously. I don't know the exact reason. Like If i provide 5 values 123, 25, 100, 46, 85 initially its loaded with this value but after that its got increasing and showing different values in the graph don't know why ? – Suthan M Jun 15 '16 at 09:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114714/discussion-between-nirav-doctorwala-and-shiv-suthan-m). – Nirav D Jun 15 '16 at 09:42
0

Yes you can pass parameter using jscript and update value on UIWebview.

Here is a useful link. Try this and apply your suitable logic. It's work form me. (This link is for objective c but it's work in swift also apply you suitable logic)

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?

Community
  • 1
  • 1
Wos
  • 390
  • 1
  • 16