简体   繁体   中英

With iOS, how to check if URL is empty

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:

嗯,试试

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

Or

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

Or Check with length of 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 }

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM