0

Im trying to convert to swift code, which sets files property to "not to backup to iCloud"

Original code looks like this

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString {
   NSURL* URL= [NSURL fileURLWithPath: filePathString];
   assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

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

I came with the such code

func addSkipBackupAttributeToItemAtURL(URL: NSURL) -> Bool{

   let fileManager = NSFileManager.defaultManager()
   assert(fileManager.fileExistsAtPath(URL.absoluteString))

   var error:NSError?
   let success:Bool = try? URL.setResourceValue(NSNumber(bool: true),forKey: NSURLIsExcludedFromBackupKey)

   if !success {
    print("Error excluding \(URL.lastPathComponent) from backup \(error)")
   } else {
    print("File at path \(URL) was succesfully updated")
   }

   return success
   }

but it throws error at line with let success:Bool

Cannot convert value of type '()?' to specified type 'Bool'

How to fix that ?

Harikrishnan
  • 6,759
  • 12
  • 54
  • 107
Alexey K
  • 5,649
  • 16
  • 51
  • 102
  • Please don't repeat questions. If the given answers are not satisfying, ask the author for clarification, or *edit* your question to provide additional information. – Martin R Dec 11 '15 at 10:01

1 Answers1

3

setResourceValue is not returning a Bool to indicate the success, but throws an error when it fails. So you should wrap it in a try catch block.

̶W̶e̶l̶l̶,̶ ̶t̶h̶e̶ ̶d̶o̶c̶u̶m̶e̶n̶t̶a̶t̶i̶o̶n̶ ̶l̶o̶o̶k̶s̶ ̶o̶u̶t̶d̶a̶t̶e̶d̶, the docs describes error handling in Swift at the bottom, but if you jump it's defenition, you would see that the method does not return anything:

public func setResourceValue(value: AnyObject?, forKey key: String) throws
Dániel Nagy
  • 10,907
  • 7
  • 44
  • 56
  • Thanks! Maybe is there another way I can check file property if it was set successfully ? – Alexey K Dec 11 '15 at 09:30
  • @AlexeyK Yes, of course, if it throws, it wasn't successful. If it doesn't throw, it was successful. – JustSid Dec 11 '15 at 09:40
  • Welcome! And for the other question, I don't know if there is another way. – Dániel Nagy Dec 11 '15 at 09:41
  • 1
    And "throws" is going to stay in Swift, so you better learn how to use it as quickly as possible. Don't even bother to find a different call, because _lots_ of calls will throw in Swift 2. – gnasher729 Dec 11 '15 at 09:45