Reputation:
My app using GCDWebServer
I get a photo from my iPhone album by using AssetsLibrary
and I store them in NSDocumentDirectory
. I just want to get access Url to this photo to show them in a web page.
There is my code :
[_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];
}];
Upvotes: 14
Views: 2569
Reputation: 4466
You can create one GET
request which will return all custom URLs of the photo assets.
After that create one handler of that custom URLs which will return requested URL image Data.
In a custom URL handler use below code
//Get PHAsset image name with extionsion.
let filename = NSURL(string: (asset as! PHAsset).originalFilename!)
// Retrive image data from PHAsset object
PHImageManager.default().requestImageData(for: asset as! PHAsset, options: nil, resultHandler: { (imageData, str, nil, info) in
//Check imageData is nil or not.
if (imageData) {
//Return image Data with contentType
let imageDatas = UIImagePNGRepresentation(imageData)
completionBlock!(GCDWebServerDataResponse(data: imageDatas, contentType: "image/\((filename?.pathExtension)!)"))
} else {
// Image retrive error message return.
let jsonResponse = ["type":"failed","Message":"Image not avilable."] as [String : Any]
completionBlock!(GCDWebServerDataResponse(jsonObject: jsonResponse))
}
})
// MARK:- Get File name from PHAsset.
extension PHAsset {
var originalFilename: String? {
var fname:String?
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: self)
if let resource = resources.first {
fname = resource.originalFilename
}
}
if fname == nil {
// this is an undocumented workaround that works as of iOS 9.1
fname = self.value(forKey: "filename") as? String
}
return fname
}
}
Upvotes: 1
Reputation: 4008
Looks like nobody is answering the actual question here: this is not about uploading a photo from iOS to a web server or viewing it in a local UIWebView, but about serving that photo using GCDWebServer
so that users can view it by connecting to the device using a web browser e.g. by going to http://my-device.local/photo-1234.jpg
.
The sample code you provided has 2 major issues:
POST
requests while you need to handle GET
requests (POST
is when submitting forms from web browsers, while GET
is for regular web browsing and getting web pages).file:///some/path/photo-1234.jpg
) instead of HTTP URL handled by GCDWebServer (e.g. http://my-device.local/photo-1234.jpg
). File URLs do not make sense outside of the device itself and will not work.If you have all the photos as files in your documents folder, you can simply add a GET
handler to GCDWebServer to serve the contents of the entire documents folder:
[webServer addGETHandlerForBasePath:@"/"
directoryPath:<PATH_TO_DOCUMENTS_DIRECTORY>
indexFilename:nil
cacheAge:3600
allowRangeRequests:YES];
This is not a very good solution though, as it requires copying photos from the assets library into the documents folder, which is wasteful. Instead, consider dynamically serving the photo assets as I explain in my answer to a related question here: https://stackoverflow.com/a/31778726/463432.
Upvotes: 2
Reputation: 393
Try this code.
GCDWebServer* webServer = [[GCDWebServer alloc] init];
[webServer addGETHandlerForBasePath:@"/" directoryPath:[[NSBundle mainBundle] bundlePath] indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
[webServer runWithPort:8080];
Upvotes: 4
Reputation: 3547
For DocumentDirectory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, 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];
For Bundled resource
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];
Upvotes: 5