In my app I have added one .flac file in my resources folder. I want to send to this .flac file to Google's speech recognition service... Below is my code:
NSURL* urlGoogle = [NSURL URLWithString:#"https://www.google.com/speech-api/v1/recognize"];
NSMutableURLRequest *urlGoogleRequest = [[NSMutableURLRequest alloc]initWithURL:urlGoogle];
[urlGoogleRequest setHTTPMethod:#"POST"];
[urlGoogleRequest addValue:#"audio/x-flac; rate=16000" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* error = nil;
NSArray *docDirs = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [docDirs objectAtIndex:0];
NSString *path = [[docDir stringByAppendingPathComponent:#"surround88"]
stringByAppendingPathExtension:#"flac" ];
NSURL* url = [NSURL fileURLWithPath:path];
//Here I'm getting flacData value is nil
NSData *flacData = [NSData dataWithContentsOfURL:url]; //flacData = nil
[urlGoogleRequest setHTTPBody:flacData];
NSData* googleResponse = [NSURLConnection sendSynchronousRequest:urlGoogleRequest
returningResponse:&response
error:&error];
id jsonObject=[NSJSONSerialization JSONObjectWithData:googleResponse options:kNilOptions error:nil];
NSLog(#"Googles response is: %#",jsonObject);
Since I'm not sending any data to the server, I'm getting empty response.
I have tested other 3rd party apis like openears, dragon, ispeech etc and not satisfied.
Can some one help me how to proceed to further. Is this the correct way to implement google's speech recognition functionality? Any help would be appreciated.
Since you're placing the file in your resources folder, you're not going to find it with NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);. That's why [NSData dataWithContentsOfURL:url] is returning nil.
Your file is now placed in your Bundle, so try loading the file's contents with this:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"surround88" withExtension:#"flac"];
NSData *flacData = [NSData dataWithContentsOfURL:url];
EDIT: based on comments bellow
Make sure the file is a member of the target you're building. In other words:
Select your .flac file
Make sure to check the boxes for the targets you're testing this with
Using the test project above, I was able to successfully create an NSData object from the .flac file.
Related
I am creating a file like so:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
}
_previewItemURL = [NSURL fileURLWithPath:filePath];
and I am displaying it in an UIDocumentInteractionController like so:
if (_previewItemURL) {
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:_previewItemURL];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
However, sometimes the PDF file I am saving off bytes are way too big, sometimes 5.5MB, which causes UIDocumentInteractionController to some time to load the PDF. I was doing some reading here https://stackoverflow.com/a/27863508/979331 and it is suggested to create a 'mapped' file. My question is I don't understand how to create one. I have been googling like crazy for the past two days and I just don't understand it.
I think the issue is with the PDF because I tried this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pgnPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf", #"example"]];
//filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
//if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSString *newFile = [[NSBundle mainBundle] pathForResource:#"example" ofType:#"pdf"];
[[NSFileManager defaultManager] copyItemAtPath:newFile toPath:pgnPath error:&error];
//[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
//}
//_previewItemURL = [[NSBundle mainBundle] URLForResource:#"example" withExtension:#"pdf"];
_previewItemURL = [NSURL fileURLWithPath:pgnPath];
with a PDF that was 5.5MB and everything seemed fine, could the issue be with how I getting the PDF? I am getting the bytes from a web service, here is my call:
task = [dataSource.areaData GetPDFFileTestTwo:[NSString stringWithFormat:#"%#",encodedUrlStr] completion:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
NSData *dataBytes;
for (NSDictionary *dict in tableArray) {
NSString *base64 = dict[#"data"];
dataBytes = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
}
if (dataBytes) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
}
_previewItemURL = [NSURL fileURLWithPath:filePath];
if (_previewItemURL) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:_previewItemURL];
documentInteractionController.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
[documentInteractionController presentPreviewAnimated:YES];
});
});
}
}
}];
And here is GetPDFFileTestTwo
-(NSURLSessionDataTask *)GetPDFFileTestTwo:(NSString *)PDFFile completion:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?PDFFile=%#",kIP,PDFFile];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if(completionHandler)
{
completionHandler(data, response, error);
}
}];
[dataTask resume];
return dataTask;
}
kIP is a string and that is the web service URL
You're not "creating" a mapped file. You're reading it into NSData as mapped to the bytes in the file. That means, that in-memory NSData bytes are underneath mapped to bytes in the file.
Here is a way to read a file as mapped:
https://github.com/atomicbird/atomictools/blob/master/NSData%2BreallyMapped.h
If you can't pass NSData to the controller for preview, mapping makes no sense. Even if you can, you have to be sure that controller won't copy your data before it is used.
Consider using PDFKit framework, where you can initialize PDFDocument with NSData and display it in PDFView.
Your questions;
create a 'mapped' file. My question is I don't understand how to
create one.
So let me point out that UIDocumentInteractionController has no inputs that accept NSData, so you wouldn't be able to create a memory mapped file to use with it. I also examined the header for any other clues, and didn't find any.
https://developer.apple.com/documentation/uikit/uidocumentinteractioncontroller
In looking for a solution, I saw that QLPreviewController mentions 'data' but I find it didn't accept NSData either.
https://developer.apple.com/documentation/quicklook/qlpreviewcontroller
I finally settled on WKWebView in WebKit, which does support using NSData, that is Memory Mapped, and loads quite quickly with a 15 MB PDF full of pictures and text I made.
I created a project with the large PDF and tried it out, it works fine. Please feel free to examine it.
https://github.com/eSpecialized/PDFDocViewerMapped
How 'mapped' works;
Anything that can take NSData can use a mapped file unless it needs the entire set of data at once. A PDF with a single image vs a multipage PDF are good examples of what can't be mapped and what can be mapped.
NSError *errors;
NSData *docFileData = [NSData dataWithContentsOfFile:docFileWithPath options:NSDataReadingMappedAlways error:&errors];
Options for NSData mapped;
https://developer.apple.com/documentation/foundation/nsdatareadingoptions?language=objc
NSDataReadingMappedIfSafe // Hint to map the file in if possible and safe
NSDataReadingMappedAlways // Hint to map the file in if possible. This takes precedence over NSDataReadingMappedIfSafe if both are given.
could the issue be with how I getting the PDF?
Fetching a PDF remotely means you must download the document.
Think of what you are doing, fetching the Pdf, saving it locally, then opening it in the UIDocument Interaction controller which takes URL's and not NSData.
I hope this meets your criteria for a solution;
UIDocumentInteractionController limitations with requiring URL's
WKWebView - allows using NSData that can be memory mapped.
3rd party options for PDF viewing - anything that can accept NSData is a
candidate for use. Look for CocoaPods and on GitHub for PDF, iOS PDF,
etc.
I am currently working on a iOS application in which I show a download link to download a Excel sheet. I want to save that downloaded file to a location of my iOS device where all my downloaded applications are stored by default, so that I can access it later form my device without opening the application.
Like in android devices, files are stored in my files from where we can access them later on.
Is there any approach to achieve this in iOS.
You can store directly on Document Directory as below
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"tempfile"]]; // It may change according to your need
NSError * error = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&error];
Here ,imageData is my data to be write on Document directory
And by saving on Document Directory you can get it from there
NSString * str = "Your Url"
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:str]
cachePolicy:NSURLCacheStorageAllowed
timeoutInterval:20];
NSURLResponse *response;
NSError *error;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[data writeToFile:filePath atomically:YES];
You can try with it for once
// NSData downloads any file from an URL
NSURL* url = [NSURL URLWithString:#"http://192.168.0.8/PoweredByMacOSX.gif"];
NSData* data = [NSData dataWithContentsOfURL:url];
// get the documents directory
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* documentsDir = documentsDirectory = [pathArray objectAtIndex:0];
NSString* localFile =
[documentsDir stringByAppendingPathComponent:#"webfile.png"];
// write the downloaded file to documents dir
[data writeToFile:localFile atomically:YES];
The below is the attribute where I send my image to the server to get the information about the image.
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"en_US", #"image_request[locale]", #"en", #"image_request[language]",[NSURL URLWithString:#"<file url>"], #"image_request[image]", nil];
To upload the image am using the code below :
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
But the parameter is asking me to provide the url.Is there any way that as soon as I snap a photo and upload it to server and get that url and append that in the parameter or any alternative to be found.And am using Unirest http library to send the request.
In order to transmit an image captured with the camera to CamFind API using Unirest, you need to same the image first.
// Get the path to the Documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [paths objectAtIndex:0];
// Get the path to an file named "tmp_image.jpg" in the Documents folder
NSString *imagePath = [documentDirectoryPath stringByAppendingPathComponent:#"tmp_image.jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
// Write the image to an file called "tmp_image.jpg" in the Documents folder
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[imageData writeToURL:imageURL atomically:YES];
// Now construct the parameters that will be passed to Unirest
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"en_US", #"image_request[locale]", #"en", #"image_request[language]", imageURL, #"image_request[image]", nil];
// And the headers
NSDictionary* headers = [NSDictionary dictionaryWithObjectsAndKeys:#"<mashape-key>", #"X-Mashape-Authorization", nil];
// Call the API using Unirest
HttpJsonResponse* response = [[Unirest post:^(BodyRequest* request) {
[request setUrl:#"https://camfind.p.mashape.com/image_requests"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJson];
I want to save a lot (800-2000) images from server to iPhone app directory (Documents directory).
First of all I have to check if those image are already on the iPhone directory.
I use this code to download one image:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"pkm.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[thedata writeToFile:localFilePath atomically:YES];
Please help me, any suggestions:
1. Save all images with the original name on iPhone directory, NOT "pkm.jpg"
2. Save images with names: from 05052008321_bigger to 05052008350_bigger
3. Check if images are downloaded already, DON'T Download again.
I know, maybe this is more than a question. But some suggestions, directions will be really good.
Thanks in advance.
A couple of reactions:
You're initiating a NSURLConnection connectionWithRequest (which triggers the NSURLConnectionDataDelegate methods), but you then apparently disregard that and initiate a dataWithContentsOfURL. You should pick one or the other, but don't do both.
I'd suggest you pursue a NSOperation-based solution because you'll definitely want to (a) enjoy concurrency; but (b) limit the concurrent operations to some reasonable number (say 4 or 5), otherwise you'll have requests timing out and failing.
In terms of getting the filename, you can retrieve the filename using lastPathComponent from the NSURL. (My download operation, used below, actually will automatically use this if you don't provide an explicit filename.)
You haven't illustrated how you're determining the list of filenames from the remote server, so we'd have to see how you know what images there are to retrieve.
If this is for your own purposes, this is fine, but I've heard claims that Apple rejects apps that request too much data over a cellular connection (and 2000 images would certainly qualify). Frankly, even if Apple doesn't raise a fuss, you really should be asking the user before using that much of their data plan. You can use Reachability to determine whether the user is connecting via wifi or via cellular, and if the latter, you may want to present a warning.
But I'd suggest something that looks like (assuming you have some NSArray with NSString versions of the URL's ... obviously adjust this for whatever form your list of URLs is in):
NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
downloadQueue.maxConcurrentOperationCount = 4;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
for (NSString *urlString in urlStrings)
{
NSURL *url = [NSURL URLWithString:urlString];
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
if (![fileManager fileExistsAtPath:path]) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithURL:url];
downloadOperation.downloadCompletionBlock = ^(DownloadOperation *operation, BOOL success, NSError *error) {
if (error) NSLog(#"download of %# failed: %#", operation.url, error);
};
[downloadQueue addOperation:downloadOperation];
}
}
And that download operation might be something like this. Obviously, use whatever NSOperation based downloader you want, but I'd suggest you use one that doesn't load the whole download into memory, but rather one that streams it directly to persistent storage.
If you don't want to get that fancy, you could just do something like:
NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
downloadQueue.maxConcurrentOperationCount = 4;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
for (NSString *urlString in urlStrings)
{
NSURL *url = [NSURL URLWithString:urlString];
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
if (![fileManager fileExistsAtPath:path]) {
[downloadQueue addOperationWithBlock:^{
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
NSData *data = [NSData dataWithContentsOfURL:url];
if (data)
[data writeToFile:path atomically:YES];
}];
}
}
Clearly, use whatever download operation class you want for downloading, but hopefully you get the basic idea. Create a NSOperation-based download, and then submit one for every file that needs to get downloaded.
I'm not sure the best method to serialize the information (naively, you could just write the NSDictionary to the disk). I would have a large NSDictionary (which could be broken up into smaller ones, up to you how to do that). The NSDictionary would take the image name "05052008321_bigger" and map it to a simple #YES.
When the app is in a position to download a new image, it would read the NSDictionary from disk (can be read in a different thread), and check if the image name is in the dictionary. This allows lookups to be fast.
- (BOOL)checkIfImageHasBeenDownloaded:(NSString *)imageName
{
return [self.dictionaryNames objectForKey:imageName] != nil;
}
I am receiving a JSON response and am currenlty able to make use of the data within my app.
I would like to save this response to a file so I could reference within an JS file located inside my project. I have already requested this data once when the application is launched so why not save it to a file and reference that throughout so only one call is needed for the data.
The HTML files for my UIWebView are imported into my Xcode project using the "create folder reference" option and the path to my JS file is html->js->app.js
I want to save the response as data.json somewhere on the device and then reference inside my js file like this request.open('GET', 'file-path-to-saved-json.data-file', false);
How can I achieve this?
After working with the idea some more here is what I came up with.
When the application is installed there is a default data file in the package that I copy to the Documents folder. When the application didFinishLaunchingWithOptions runs I call the following method:
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://path-to-live-file.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
Then throughout the application when I need to reference the data, I use the saved file.
//application Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *jsonError = nil;
NSString *jsonFilePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath options:kNilOptions error:&jsonError ];
To reference the json file in my JS code, I added a URL parameter for "src" and passed the file path to the Applications Documents folder.
request.open('GET', src, false);