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];
Related
I need to download pdf file which I get in api response as a base64string.
How should I save it locally based on cell tag and preview it using documentcontroller?
Eg-api response is an array of dictionaries with different pdf files where we have a key called "pdf":"zcvffaewww.."
I need to download these pdf files on tap of uibutton on uitableviewcell and preview it in documentcontroller.
Please help.
Thanks.
you are getting a base64 string in JSON, it means you are getting the file name and file type also right (if not getting then it is fine)
Step 1: Instead of download, you can view that PDF in webView. Here is the way to do this,
// convert your base64 string into NSData
NSData* myData = [NSData dataFromBase64String: yourBase64String];
then write below code to show pdf in webView,
[_webView loadData:myData
MIMEType:#"application/pdf"
textEncodingName:#"NSUTF8StringEncoding"
baseURL:[NSURL URLWithString:#"https://www.google.co.in/"]];
// zooming pdf view
_webView.scalesPageToFit = YES;
_webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
It will show pdf in webView
step 2: for downloading pdf, write code
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:#"data:application/pdf;base64,%#",
numStr]];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.pdf"];
[urlData writeToFile:filePath atomically:YES];
}
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.
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];
I'm basically trying to find a way to save a JSON server response, so can work on some app logic that relies on the response even when the server is no longer returning it. When I get the data back, I can print it out and it will look something like this:
<7b202254 7269704c 69737422 3a207b22 43757272 656e7454 696d6522 3a203134 30353037 33323836 ...
Is there any way I can create an instance of NSData using this information (NSData dataWithData?)? Or is there a way to create JSON dict/array with the JSON string?
TL;DR how do I save a JSON server response and add a debug option to fake the server response?
You can directly save the jsonData (NSData) into a file, and use it, see below
{
//Write NSData directly to file
[jsonData writeToFile:[self jsonFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
//Read from file
NSJSONSerialization *json=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[self jsonFilePath]] options:0 error:nil];
//The json object can be used as an Array or, Dictionary
NSArray *array=(NSArray *)json;
//OR
NSDictionary *dic=(NSDictionary *)json;
}
-(NSString *)jsonFilePath{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:#"file.json"];
}
Hope it helps.
Cheers.
You Json Response data is image data . You can store it in document directory as below.
NSData *webData = UIImageJPEGRepresentation(image1, 0.5);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Profile1.jpeg"];
[webData writeToFile:savedImagePath atomically:YES];
Now in your Document Directory store image. check go to Iphone Simulator > Application > ProjectName > Documents
Store JSON in text file, as suggested by other.
Now where you want to fetch this text file data, you can use -
NSString *jsonFilepath = [[NSBundle mainBundle] pathForResource:#"jsonFile" ofType:#"text"];
// JSON Data
NSData *data = [NSData dataWithContentsOfFile: jsonFilepath];
// JSON String
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:jsonFilepath encoding:NSUTF8StringEncoding error:nil];
Now you can perform all operation with JSON, as you want.
You can save your JSON Data as a plist in your App's Document Folder..
-(void)SaveResponse
{
NSError *error = nil;
NSData *JSONData = Your Current Data that received from server
NSMutableDictionary *objDictionary = [NSJSONSerialization
JSONObjectWithData:JSONData
options:NSJSONReadingAllowFragments
error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strFilePath = [documentsDirectory stringByAppendingPathComponent:#"Response.plist"];
[objDictionary writeToFile:strFilePath atomically:YES];
}
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);