简体   繁体   中英

Using images and css file for a generated HTML UIWebView

I'm generating an HTML file for an app, and in this HTML file there's a link to a stylesheet and one to an image.

Here's what I tried so far:

NSMutableString *toReturn = [NSMutableString stringWithCapacity:100];
NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"etapes.css" ofType:nil];

[toReturn appendFormat:@"<html><head><title></title><link href=\"%@\" media=\"all\" rel=\"stylesheet\" type=\"text/css\" /></head><body>", cssPath];

It generates the right full path to the right file, this is okay if I want to access it on my mac, but on the simulator or my iPhone it doesn't point to the right place at all...

Do you have any idea of how could I make this?

Thanks

I found this tutorial a while back. I ended up just using a <style> tag in the end though.

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

Another way of doing this is like so:

-(NSString *)urlForFileNamed:(NSString *) name ofType:(NSString *) type {
  NSString *filePath = [[NSBundle mainBundle] pathForResource: name ofType: type];
  if (!filePath) { NSLog(@"No path found for file %@.%@", name, type); }
  return filePath;
}

-(void)viewDidLoad {
  [super viewDidLoad];

  NSString *path = [[NSBundle mainBundle] bundlePath];
  baseUrl = [NSURL fileURLWithPath: path];

  [view loadHTMLString: [self html] baseURL: [NSURL fileURLWithPath: path]];
}

-(NSString *)html {
  // Obviously the below's just a stub for proper HTML
  return [NSString stringWithFormat: @"<img src=\"@\" />", [self urlForFileNamed: @"foo" ofType: @"png"]];
}

You may try to edit the line

NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"etapes.css" ofType:nil];

to

NSString *cssPath = [[NSBundle mainBundle] pathForResource:@"etapes" ofType:@"css"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM