2013-05-02 3 views
5

Я совершенно не знаком с HighCharts, и я привел пример http://blog.li-labs.com/developing-ios-apps-with-custom-charting/ и пробовал то же самое, но на iPad-симуляторе я получаю пустой экран.Как добавить Highcharts в UIWebView в iOS?

Я задал вопросы о переполнении стека, но все же он не работает. Может кто-нибудь сказать, где я иду не так.

EDIT: код в моем HTML-файле:

<!DOCTYPE HTML> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <title>Highcharts Example</title> 

     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
     <script type="text/javascript"> 
$(function() { 

     // Radialize the colors 
     Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function(color) { 
      return { 
       radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 }, 
       stops: [ 
        [0, color], 
        [1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken 
       ] 
      }; 
     }); 

     // Build the chart 
     $('#container').highcharts({ 
      chart: { 
       plotBackgroundColor: null, 
       plotBorderWidth: null, 
       plotShadow: false 
      }, 
      title: { 
       text: 'Browser market shares at a specific website, 2010' 
      }, 
      tooltip: { 
       pointFormat: '{series.name}: <b>{point.percentage}%</b>', 
       percentageDecimals: 1 
      }, 
      plotOptions: { 
       pie: { 
        allowPointSelect: true, 
        cursor: 'pointer', 
        dataLabels: { 
         enabled: true, 
         color: '#000000', 
         connectorColor: '#000000', 
         formatter: function() { 
          return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; 
         } 
        } 
       } 
      }, 
      series: [{ 
       type: 'pie', 
       name: 'Browser share', 
       data: [ 
        ['Firefox', 45.0], 
        ['IE',  26.8], 
        { 
         name: 'Chrome', 
         y: 12.8, 
         sliced: true, 
         selected: true 
        }, 
        ['Safari', 8.5], 
        ['Opera',  6.2], 
        ['Others', 0.7] 
       ] 
      }] 
     }); 
    }); 


     </script> 
    </head> 
    <body> 
<!--<script src="../../js/highcharts.js"></script>--> 
<!--<script src="../../js/modules/exporting.js"></script>--> 

<script type="text/javascript" src="highcharts.js"></script> 
<script type="text/javascript" src="exporting.js"></script> 

<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> 
    </body> 
</html> 

How to add and use the Javascript libraries in XCode

Here is a simple view of how I handle the code and data within XCode.

  1. Download the Javascript reporting package from your preferd chart site. In my case: http://www.highcharts.com/download

  2. Add or import the files into XCode resources. (I suggest creating a group called JS).

  3. When adding a resource to XCode it will generally be marked as being needed to be compiled. Ensure that the files are not listed as being “Compiled”. The easiest way is to simply drag the files from Targets -> Your Project Name -> Compiled Sources into Targets -> Your Project Name -> Copy Bundle Resources.

  4. Create a test html file or simply import one from your HighChart (or any other javascript chart library) examples folder. In my case I name it hcpie.html

  5. Ensure that any file references in the tags do not recurse or move into any folder (even if they are in one in your project). e.g.

RIGHT =

WRONG =

  1. Create a UIWebView within Interface Designer and link it to your view (in my case I named it chart1). e.g.

@interface FirstViewController : UIViewController { IBOutlet UIWebView *chart1; }

@end

  1. Simply reference the HTML example file when loading.

    • (void)viewDidLoad {

NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@”hcpie” ofType:@”html”]; NSString *htmlText = [NSString stringWithContentsOfFile:pathOfFile encoding:NSUTF8StringEncoding error:nil];

NSURL *baseURL = [NSURL fileURLWithPath:pathOfFile];

[chart1 loadHTMLString: htmlText baseURL:baseURL];

[super viewDidLoad];

}

+0

Highcharts имеет свою обертку iOS. – Raptor

ответ

6

шагов: -

1) Первый раз создающие один HTML файл и сделать необходимый код или для испытания может скопировать HTML код из примеры, которые вы получаете из пакета http://www.highcharts.com/download

2) Убедитесь, что скрипты в html должны иметь соответствующие .js ссылки , например: - <script src="http://code.highcharts.com/highcharts.js"></script>

или

, если вы хотите, чтобы локально вы можете написать <script src="highcharts.js"></script> Но убедитесь, что .js файлы есть в папке приложения.

3) NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"graph" ofType:@"html"]; 
    NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil]; 
    [obj loadHTMLString:htmlString baseURL:nil]; // Webview *obj; 

Надеюсь, это поможет вам. В моем случае это работает.

+0

Я пробовал, как вы упомянули. Тем не менее он не работает. Просто проверьте мой файл html так же. Я отредактировал вопрос. Осталось – parilogic

+2

написать в части тела вместо LittleIDev

+0

Я запускаю ваш html, изменяя, как описано выше. И это работает. Пожалуйста, дайте мне знать, это работает для вас? – LittleIDev

1

Я пробовал предложения в этом посте и не мог получить нагрузку HighChart.

Проблема заключалась в вызове loadHTMLString. Недопустимый проход для baseURL. Вот что работал для меня - мне нужно, чтобы передать фактическое BaseUrl:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:url ofType:@"html"]; 
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil]; 

NSURL *baseURL = [NSURL fileURLWithPath:htmlFile]; 

[webView loadHTMLString:htmlString baseURL:baseURL]; 
+0

Я тоже это пробовал, но для меня он отлично открывается в Safari в Mac, но не работает в симуляторе. Любая помощь. –

+0

'NSString * htmlFile = [[NSBundle mainBundle] pathForResource: @" line "ofType: @" htm "]; NSString * htmlString = [NSString stringWithContentsOfFile: htmlFile encoding: NSUTF8StringEncoding error: nil]; UIWebView * obj = [[UIWebView alloc] initWithFrame: CGRectMake (0, 100, self.contentView.frame.size.width, 650)]; obj.delegate = self; [self.contentView addSubview: obj]; NSURL * baseURL = [NSURL fileURLWithPath: htmlFile]; [obj loadHTMLString: htmlString baseURL: baseURL]; ' –

+0

@BalramTiwari мой ответ работает в симу, на реальных устройствах и т. д. Возможно, вы не копируете все свои ресурсы .js на устройство? Вы можете проверить свою конфигурацию проекта, в частности раздел «Ресурсы копирования ресурсов» на вкладке «Сборка фаз» вашего проекта. – DiscDev

0

Полезный код для вызова .html в UIWebView.

-(void)viewDidLoad 
    { 
    NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"chart" ofType:@"html"]; 

    NSString *htmlText =[NSString stringWithContentsOfFile:pathOfFile encoding:NSUTF8StringEncoding error:nil]; 

    NSURL *baseURL = [NSURL fileURLWithPath:pathOfFile]; 

    [UIWebView loadHTMLString: htmlText baseURL:baseURL]; 
    } 
Смежные вопросы