With iOS, how to check if a URL is blank

I download JSON, but I want to check the "URL": "", in 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: 
+6
source share
7 answers

Hmm try

 if ([URL isEqualToString:@"The URL?"]) { 
+5
source
 if (URL == [NSNull null]) { //... } else { //... } 

Or

 if (URL == nil) { //... } else { //... } 

Or Check URL Length

+3
source

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 NSURL, you can use:

 if([[url absoluteString] isEqualToString:@""]) { //empty } 
+2
source

When working with JSON data, I try to be very careful. Say I have JSON deserialized in an NSDictionary. In doing so, I need to pull the string associated with the URL key from the dictionary and turn it into NSURL. Also, I'm not 100% sure about JSON or 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 that, the URL will have a null or valid URL. -isKindOfClass: preempts the value of NSDictionary, NSArray, NSNumber, or NSNull. -length> 0 filters out an empty string (which, as you know, can ruin NSURL). Additional paranoia of decoding and then re-encoding of URL screens processes partially encoded URLs.

+2
source

Depending on how it is stored, you may need to check if it is null ( URL == nil ), or if the string is empty. Assuming your url is stored in an NSString, you would like something like:

 BOOL empty = URL == nil || [URL length] == 0; 
0
source

Try it. It worked for me.

 NSURL *url; if ([url path]) { // url is not empty } else { // url is empty } 
0
source
 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]; } 
0
source

Source: https://habr.com/ru/post/915987/


All Articles