-2

My Swift code is not working after converting to Swift2.2. My code :

Swift 1.0 code:

Class func getPath(filename:  String ) -> String {
return NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true)[0].stringByAppendingComponent(filename)
}

error : Use URLByAppendingPathComponent On NSURL instead.

halfer
  • 19,824
  • 17
  • 99
  • 186
MilkBottle
  • 4,242
  • 13
  • 64
  • 146

2 Answers2

2

Use the URL related API and the modern way to get the documents directory:

In Swift 2 class functions are marked with static

static func getPath(filename:  String ) -> String {
  // try! is safe
  let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
                                             inDomain: .UserDomainMask,
                                             appropriateForURL: nil,
                                             create: true)
  return documentDirectory.URLByAppendingPathComponent(filename).path!
}

or completely URL based:

static func getURL(filename:  String ) -> NSURL {
   let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
                                           inDomain: .UserDomainMask,
                                           appropriateForURL: nil,
                                           create: true)
   return documentDirectory.URLByAppendingPathComponent(filename)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0
Class func getPath(filename:  String ) -> String {
    let basePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let baseURL = NSURL(fileURLWithPath: basePath)
    let fullURL = baseURL.URLByAppendingPathComponent(filename)
    return fullURL.path!
}
Alexander
  • 59,041
  • 12
  • 98
  • 151