Armin Scheithauer
Armin Scheithauer

Reputation: 598

Using NSNumber numberWithBool in Swift

I submitted my Version 2 of my app for review and it got rejected due to a high backup to iCloud - wasn't aware of this as I only have to pics in my app but anyway. Now I try to convert that code

NSError *error = nil;
    NSURL *databaseUrl = [NSURL fileURLWithPath:databasePath];
    BOOL success = [databaseUrl setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
    if(!success){
    NSLog(@"Error excluding %@ from backup %@", [databaseUrl lastPathComponent], error);
    }

to swift and I couldn't get it work... This is what I have so far...

func excludeFromBackup() {
    var error:NSError?
    var fileToExclude = NSURL.fileURLWithPath("path")
    var success:Bool = fileToExclude?.setResourceValue(NSNumber.numberWithBool(true), forKey: NSURLIsExcludedFromBackupKey, error: &error)
    if success {
        println("worked")
    } else {
        println("didn't work")
    }
}

As you see, I fail with the numberWithBool Value.

Can anyone help me? Did anyone convert it before?

Thanks in advance...

Upvotes: 4

Views: 6694

Answers (2)

Martin R
Martin R

Reputation: 539775

Some Swift types (Int, Bool, String, ...) are automatically bridged to the corresponding Objective-C type, so you can simply write:

let success = fileToExclude.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey, error: &error)

(More details in Working with Cocoa Data Types.)

Upvotes: 6

Armin Scheithauer
Armin Scheithauer

Reputation: 598

I got it sorted... Here is the solution.

func excludeFromBackup(path:String) {
        var error:NSError?
        var fileToExclude = NSURL.fileURLWithPath(path)!
        var success:Bool = fileToExclude.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey, error: &error)
        if success {
            println("worked")
        } else {
            println("didn't work")
        }
    }

That works just fine now.

Thanks anyway...

Upvotes: 3

Related Questions