我的应用程序使用GCDWebServer我通过使用AssetsLibrary从我的iPhone专辑中获取照片,并将它们存储在NSDocumentDirectory中.我只想访问此照片的网址,以便在网页中显示.
有我的代码:
[_webServer addHandlerForMethod:@"POST" path:@"/" requestClass:[GCDWebServerURLEncodedFormRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) { ALAsset *asset = [self.arrayPictures objectAtIndex:0]; ALAssetRepresentation *rep = [asset defaultRepresentation]; CGImageRef iref = [rep fullResolutionImage]; UIImage *thumbnail = [UIImage imageWithCGImage:iref]; NSString* path ; if (thumbnail != nil) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; path = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"test.png"]]; NSData* data = UIImagePNGRepresentation(thumbnail); [data writeToFile:path atomically:YES]; } NSURL *url = [NSURL fileURLWithPath:path]; NSString* html = [NSString stringWithFormat:@"<html><body><img src=\"%@\" width=\"400\" height=\"500\"/></body></html>",url]; return [GCDWebServerDataResponse responseWithHTML:html]; }];
解决方法
对于DocumentDirectory路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *imagePath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"test.jpg"]]; NSURL *baseURL2 = [NSURL fileURLWithPath:documentsDirectory]; NSString* html2 = [NSString stringWithFormat:@"<html><body><img src=\"%@\" width=\"400\" height=\"500\"/></body></html>",imagePath]; [_webView loadHTMLString:html2 baseURL:baseURL2];
捆绑资源
NSString *path = [[NSBundle mainBundle] pathForResource:@"ahsan" ofType:@"jpg"]; // path to your image source. NSURL *baseURL = [NSURL fileURLWithPath:path]; NSString* html = [NSString stringWithFormat:@"<html><body><img src=\"%@\" width=\"400\" height=\"500\"/></body></html>",path];