With iOS, how to check if URL is empty - ios

I'm loading an JSON but i want to check of the "URL": "", in the json is empty sometimes the ID is empty how can i check?
if(URL == HOW TO CHECK IF EMPTY?)
{
}
else
{
}
Error:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:

Hmm, try
if ([URL isEqualToString:#"The URL?"]) {

If the URL object is a string, you can use either,
if([string length] == 0) { //empty }
or
if([string isEqualToString:#""]) { // empty }
If the URL object is an NSURL, you can use:
if([[url absoluteString] isEqualToString:#""]) { //empty }

if (URL == [NSNull null]) {
//...
} else {
//...
}
Or
if (URL == nil) {
//...
} else {
//...
}
Or Check with length of URL

When working with JSON data I tend to be very careful. Let's say I have a JSON deserialized into a NSDictionary. With that, I need to pull a string associated with the key "URL" out of the dictionary and turn it a NSURL. In addition, I'm not 100% confident in the JSON or the string value.
I would do something like this:
NSURL *URL = nil;
id URLObject = [JSON valueForKey:#"URL"];
if ([URLObject isKindOfClass:[NSString class]] && [URLObject length] > 0) {
URLObject = [URLObject stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
URLObject = [URLObject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
URL = [NSURL URLWithString:URLObject];
}
After this, URL will have either a nil or a valid URL. -isKindOfClass: weeds out the value being an NSDictionary, NSArray, NSNumber, or NSNull. -length > 0 filters out empty string (which, as you know, can mess up an NSURL). The extra paranoia of decoding then re-encoding the URL escapes handles partially encoded URLs.

if (url.absoluteString.length==0)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Please enter a url" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}

Depending on how it is stored, you may need to verify if it is null (URL == nil) or if the string is empty. Assuming your URL is stored in an NSString, you would go for something like:
BOOL empty = URL == nil || [URL length] == 0;

Try this. It worked for me.
NSURL *url;
if ([url path])
{
// url is not empty
}
else
{
// url is empty
}

For swift 3 and swift 4 use this
var UrlUploadVideo = NSURL()
if UrlUploadVideo.absoluteString == "" {
// your code
}

guard let url = URL(string: urlStr) else { return }

Related

Check if contain Null

When I print the following I get (null)
NSLog(#"%#", [[responseObject objectAtIndex:i] objectForKey:#"child"]);
Now I want to do a validation to check if it returns (null). How am I supposed to do this?
I tried the following but it doesn't work:
1.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqualToString:#"(null)"]) {
}
2.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqual:#"(null)"]) {
}
"null" isn't just a NSString. You should do some research into the concept of a null object.
What you're looking for can be written like this:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
//key "child" not in dictionary
}
(null) is the representation of nil displayed by NSLog.
You can write the following:
if ([[responseObject objectAtIndex:i] objectForKey:#"child"] == nil) {
}
Or a shorter alternative:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
}
Another way to check is to use string length. I know other answers are just as good, I am just giving OP and anyone else in future some more options.
NSString *childStr = [[responseObject objectAtIndex:i]objectForKey:#"child"];
if ([childStr length] < 1)
{
//no value specified - childStr is NULL
}
else
{
//there is something in the childStr - throw a party!
}
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"hello"]) {
NSLog(#"only if not null show %#",[defaults objectForKey:#"hello"]);
}
This is a way to check it from User Defaults. It will only print if the saved object does not equal null.

How to compare NSString with NSString nil Value? [duplicate]

This question already has answers here:
How to detect if NSString is null?
(5 answers)
Closed 8 years ago.
I'm new to iOS development. I get an error when I compare NSString with NSString nil value. It is not working in if condition.
my code is:
NSDictionary *responseFromJSON = [JSON objectForKey:#"response"];
NSString *strResponseMsg = [responseFromJSON objectForKey:#"104"];
if ([strResponseMsg isEqualToString:nil])
{
NSLog(#"login Invalid");
}
else
{
NSLog(#"login success");
}
You can simply do like this,
NSString * string = nil;
if (string!=nil && // not nil, means 0x0 object
string.length>0 && // at leaset one character should exists
[string isEqual:[NSNull null]]) { // to avoid 'null' in string
// valid string
}
You can do like this,
if ([yourString isEqual:[NSNull null]])
{
//your code goes here
}
Hope this helps.
Use below
NSString *strResponseMsg = [responseFromJSON objectForKey:#"104"];
if (!strResponseMsg)
{
NSLog(#"login Invalid");
}
else
{
NSLog(#"login success");
}
If you want to check the NSString whether it's nil or empty.
You just need to do something like that:
if (strResponseMsg.length) {}
Because it will not go inside if the strResponseMsg is nil or empty. It will only go inside when strResponseMsg is not nil and no empty.

Check if JSON value exists - iOS

I have an iOS application which downloads and parses a Twitter JSON feed and then presents that feed in a UITableView. This all works fine but I have one question:
When the user taps a UITableView cell, the app will look into the array "tweets_links" and see if that particular tweet has an attached URL, if it does then the web view will appear.
Because not all tweets have website URLs, I have added a simple try catch statement (like in C++) which can tell me if there is an exception when trying to access that part of the array.
My question is: is this is good or bad approach to doing this??
Here is my code:
int storyIndex = indexPath.row;
int url_test = 1;
NSString *url;
#try {
url = [[tweets_links[storyIndex] valueForKey:#"url"] objectAtIndex:0];
}
#catch (NSException *problem) {
// There is NO URL to access for this Tweet. Therefore we get the out of bounds error.
// We will NOT take the user to the web browser page.
// Uncomment the line below if you wish to see the out of bounds exception.
// NSLog(#"%#", problem);
url_test = 0;
}
if (url_test == 1) {
WebBrowser *screen = [[WebBrowser alloc] initWithNibName:nil bundle:nil];
self.seconddata = screen;
seconddata.web_url = url;
screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:screen animated:YES completion:nil];
}
else if (url_test == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Info" message:#"There is no URL attatched to this Tweet." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alertView show];
[tweetTableView deselectRowAtIndexPath:indexPath animated:YES];
}
Is there a much better way of trying to achieve what I am doing???
Thanks, Dan.
Using try and catch is Objective-C isn't encouraged there are other ways checking and handling errors
// firstObject will return the first object in the array or nil if the array is empty.
url = [[tweets_links[storyIndex][#"url"]] firstObject];
if (!url) {
// handle the case for no url
} else {
// do something with url
}
Since sending a message to nil is safe in Objective-C and returns nil it's safe to chain calls. e.g. If the dictionary didn't have an object for that key, then it would return nil and sending firstObject to nil returns nil.
Using either if the below approaches will be fine because TRY CATCH is used to catch programming errors
and use
objectForKey:
instead of
valueForKey:
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil)
OR
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
I don't know a ton about the Twitter feed, but you can probably check for a nil value returned from objectForKey: like so
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil) { /* process the URL */ }
Your code assumes that the value is always an array of at least size = 1, it would be safer to inspect the #"url" key's value before assuming it's an array.
Using exceptions in Objective-C is throwned upon. Exceptions are reserved for programming errors. You don't catch them, you fix the code. With a JSON document, you never have any guarantees what you received, so just be careful.
NSString* url = nil;
NSArray* linksArray = nil;
NSDictionary* linkDict = nil;
NSArray* urlArray = nil;
if ([tweet_links isKindOfClass:[NSArray class]])
linksArray = tweet_links;
if (storyIndex >= 0 && storyIndex < linksArray.count)
linkDict = linksArray [storyIndex];
urlArray = linkDict [#"url"];
if ([urlArray isKindOfClass:[NSArray class]] && urlArray.count > 0)
url = urlArray [0];
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
Note that sending messages to a nil object always returns 0 / NO / nil as appropriate.
And please get into the habit of naming variables properly. You wrote "int url_test = 1;". What does url_test mean? I read the variable name, I have no idea what it means. I need to understand all the code. Making it "int" means it could be 0, 1, 2, 20000 or whatever. If you write instead "BOOL urlValid = YES;" that is clear: It means that you have a valid URL.
Since url value is a NSString value, you could use length to check both if it's nil and if not, if it has any value (not empty string). You can check then if this NSString is a valid url.
- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx = #"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
....
NSString *url = [[tweets_links[storyIndex][#"url"]] firstObject];
if ([url length] && [self validateUrl: url]) {
// Has a valid URL
}

NSNull isEqualToString: unrecognized selector on ObjC

Well my code was like this:
I have two strings, place and date. I am using them like this:
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
In some entries, the output is like this:
"21/10/2012, <null>"
"21/11/2012, None"
"21/12/2013, London"
My app does not crash but I want the place to be visible only when is not null and not equal to None.
So I tried this:
NSString * place=[photo objectForKey:#"place"];
if ([place isEqualToString:#"None"]) {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
}
Problem was when place was <null> my app crashed and I got this error:
[NSNull isEqualToString:] unrecognized selector send to instance
So, i tried this:
if (place) {
if ([place isEqualToString:#"None"]) {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
}
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
}
But the problem remains.
I guess your source data is coming from JSON or similar (something where data is being parsed in and missing data is being set to NSNull). It's the NSNull that you need to deal with and aren't currently.
Basically:
if (place == nil || [place isEqual:[NSNull null]]) {
// handle the place not being available
} else {
// handle the place being available
}
Use
if (! [place isKindOfClass:[NSNull class]) {
...
}
instead of
if (place) {
...
}
Note: NSNull object is not nil, so the if (place) will be true then.
Use [NSNull null]:
if ([place isKindOfClass:[NSNull class]])
{
// What happen if place is null
}

Check key exists in NSDictionary

how can I check if this exists?:
[[dataArray objectAtIndex:indexPathSet.row] valueForKey:#"SetEntries"]
I want to know whether this key exists or not. How can I do that?
Thank you very much :)
EDIT:
dataArray has Objects in it. And these objects are NSDictionaries.
I presume that [dataArray objectAtIndex:indexPathSet.row] is returning an NSDictionary, in which case you can simply check the result of valueForKey against nil.
For example:
if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:#"SetEntries"] != nil) {
// The key existed...
}
else {
// No joy...
}
So I know you already selected an answer, but I found this to be rather useful as a category on NSDictionary. You start getting into efficiency at this point with all these different answers. Meh...6 of 1...
- (BOOL)containsKey: (NSString *)key {
BOOL retVal = 0;
NSArray *allKeys = [self allKeys];
retVal = [allKeys containsObject:key];
return retVal;
}
Check if it's nil:
if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:#"SetEntries"] != nil) {
// SetEntries exists in this dict
} else {
// No SetEntries in this dict
}
this also works using Objective-C literals using the following syntax:
NSDictionary *dict = #{ #"key1" : #"value1", #"key2" : #"value2" };
if (dict[#"key2"])
NSLog(#"Exists");
else
NSLog(#"Does not exist");
Try this:
if ([dict objectForKey:#"bla"]) {
// use obj
} else {
// Do something else like create the object
}
This one does the same but with less code:
if (dataArray[indexPathSet.row][#"SetEntries"] != nil) { /* the key exists */ }
else { /* the key doesn't exist */ }
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:#"SetEntries"] != nil) {
// SetEntries exists in this dict
} else {
// No SetEntries in this dict
}
That's the right answer.
Check dictionary contains any value. I prefer [dic allKeys].count > 0 to check.
Use the (unsigned long) option:
if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:#"SetEntries"] ) {
// Key exist;
}else{
// Key not exist;
};

Resources