I'm trying to call an API and bring back menu items. My string seems to contain data because when I put it into a browser, I'm getting JSON.
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
My "urlString" contains a lot of information, but when I put a breakpoint on the NSURL object, it says it returns "nil".
EDIT: Removed spaces however the error persists.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:urlString]];
NSHTTPURLResponse *responseCode = nil;
NSError *error = [[NSError alloc] init];
NSData *ResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:ResponseData options:kNilOptions error:nil];
itemName = dataDictionary[#"item_name"];
NSLog(#"%#", itemName);
EDIT: Added request code
Ok, I have found something interesting about your url
You just forgot about string format. Every percent sign cry to you: 'I want to be replaced with something you gain to me!'
So, to prevent such behavior, you need to hide every percent with another percent: %%
-(void)doNSURLTestOne{
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%%3A20&cal_min=0&cal_max=50000&fields=item_name%%2Cbrand_name%%2Citem_id%%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}
But I prefer to use AFNetworking library for net part
UPD: better choice to use another clean NSString ( thanks #rmaddy )
-(void)doNSURLTestTwo{
NSString *urlString = #"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY";
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}
Related
I am using a NSURLConnect call and I get unsupported URL when I have a space in my query string. To fix this I converted the string to base64 and I am still getting errors. How do I send a base64 string though NSUrlConnect successfully? If this isn't possible, how do I safely send a string with a space in it?
NSData *convertData = [queryWS dataUsingEncoding: NSUnicodeStringEncoding];
queryWS = [convertData base64EncodedStringWithOptions:kNilOptions];
NSURLRequest *urlRequest =
[NSURLRequest requestWithURL:[NSURL URLWithString:queryWS]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (!error) {
responseDictionary =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:&parseError];
You do not want to convert the URL string to base64 encoding. What you want is to properly escape any special characters in the URL. Please see the NSString stringByAddingPercentEscapesUsingEncoding: method or NSString stringByAddingPercentEncodingWithAllowedCharacters: if you only need to support iOS 9 or later.
NSString *queryString = #"SOME_QUERY_STRING";
NSString *encodedQueryString = [queryString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
I have a URL like so ANC & SHO.pdf
when I encode the URL like so:
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
now when I use this URL it does not work and I have a feeling it has to do with the & because when I tried another file, it worked perfectly I was able to load the PDF, but with the file with & I was not.
What Am I doing wrong?
Here is the output of escapedString
escapedString __NSCFString * #"Ancaster%5CANC%20&%20SHO%20-%20Laundry%20Closets%20to%20be%20Checked.pdf" 0x16ea33c0
I then use that to call a method:
NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:#"%#",escapedString]];
Here is the method:
-(NSArray *)GetPDFFileData:(NSString *)PDFFile
{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?PDFFile=%#",kIP,PDFFile];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return tableArray;
}
[NSCharacterSet URLHostAllowedCharacterSet] contains characters below:
!$&'()*+,-.0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~
which contains '&', so
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
won't escape '&' for you, then it's not URLEncoded.
see the question about how to url encode a string.
I am trying to download my image and store into a directory. Every thing is working fine before updating the names of images on the server end with spaces. I am handling the spaces with the following code.
NSString *newString = [getImageUrl stringByReplacingOccurrencesOfString:#" "
withString:#"%20"];
After that I am getting the final String of URL as given below
http://www.retail-king.com/image/data/men%20jeans/pd%201/5.jpg
When I open this url in browser then the image is showing but I cannot see and download the image with this url in the app.
I am calling the following method to download the image.
-(void)downloadImageWithPath:(NSString *)_path andURL:(NSString *)_url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:_url]];
NSLog(#"pic file = %#",_path);
NSLog(#"ASI http pic url:%#",[[request url] description]);
// [request setDownloadProgressDelegate:self];
[request setShowAccurateProgress:YES];
request.shouldContinueWhenAppEntersBackground=YES;
[request setDownloadDestinationPath:_path];
[request setTimeOutSeconds:30];
// [request setDelegate:self];
[request setStartedBlock:^{
NSLog(#"request started pic");
}];
[request setCompletionBlock:^{
// Use when fetching text data
NSLog(#"request completed pic");
currentPicsCount++;
if (currentPicsCount == picsCount && totalPicsDownload ) {
NSLog(#"All pics have downloaded");
totalPicsDownload = false;
[[SingltonClass getLoadingClassReference] dataSynced];
}
}];
[request setFailedBlock:^{
NSLog(#"request failed pic");
picsCount--;
}];
[request startAsynchronous];
}
setFailedBlock is called. Which shows pic is failed to download.
Your question is ambiguous. I quickly ran a test on the URL and was able to see the downloaded image. This might not be an ideal solution, but you can understand what's going on. I used UIWebView to display the image, and the for you the tricky part could be to set the bounds of CGRectMake. How are you downloading and displaying the images?
Here is my code if it helps.
- (void)viewDidLoad
{
[super viewDidLoad];
// Added space between keyword men and jeans
NSString *url = #"http://retail-king.com/image/data/men jeans/pd%201/5.jpg";
url = [url stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
// Check for URL
NSLog(#"Final Url = %#",url);
// Displaying it on webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
NSURL *targetURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
// Program to check if the image is downloaded in directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localFilePath = [paths objectAtIndex:0];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[thedata writeToFile:localFilePath atomically:YES];
}
The image was successfully downloaded at -
/Users/raurora/Library/Application Support/iPhone Simulator/7.1/Applications/554A5C94-1D29-42F0-886D-751CD3DFB155/Library/Caches/com.stackoverflow.doubt/fsCachedData/
I am trying to request a URL and I am getting error saying
"Data parameter is nil".
I had found that the variables used has got space dot(.). I think this is the problem that is being caused by the URL. So is there any way to send URL having space and dot without crashing?
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"192.168.1.5/mobileapp?/signin=%#&%#",username,password]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
Try using NSUTF8StringEncoding
NSString *myUnencodedString = [NSString stringWithFormat:#"192.168.1.5/mobileapp?/signin=%#&%#",username,password]
NSString *encodedString = [myUnencodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *myURL = [[NSURL alloc] initWithString:encodedString]
I am trying to request the following URL and i am getting an error saying "Data parameter is nil". i had found that the 'seller_name' has got space and 'amount' has got dot(.). I think this is the problem that is being caused by the URL. So is there any way to send URL having space and dot without loosing the information?
NSURL *url1 = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1];
Take a look at the -stringByAddingPercentEscapesUsingEncoding: method in NSString, e.g.:
NSString *myUnencodedString = [NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]
NSString *encodedString = [myUnencodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *myURL = [[NSURL alloc] initWithString:encodedString]
...
Cf.: Apple documentation.
It is happening because URL should not contain white space. It should be encode to %20 if there is any space. We can encode space and special character in NSString using NSUTF8StringEncoding as below
NSString *string = [[NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [[NSURL alloc]initWithString:string];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1];