Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentsOfFile method deprecated in swift 2.2

My code in Objective-C is

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Logger.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

When I try to convert this to swift, I am not able to convert it as the method ContentsOfFile has been deprecated. Can anyone tell me how to convert that to swift? I am working with Xcode 7.2 and swift 2.2. My code in swift is

var paths : NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    var documentsDirectory : NSString = paths[0] as! String
    var filePath = documentsDirectory.stringByAppendingPathComponent("Logger.txt")
    var error:NSError?
    let content = NSString(contentsOfFile: filePath, encoding:NSUTF8StringEncoding, error: &error)
    if let theError = error {
        NSLog("\(theError.localizedDescription)")
    }
like image 492
Maneesh Sharma Avatar asked Nov 28 '22 08:11

Maneesh Sharma


2 Answers

Swift 2+

let path:String = NSBundle.mainBundle().pathForResource("Logger", ofType: "txt")!
txtContent.text = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

Swift 3+

let path:String = Bundle.main.path(forResource: "Logger", ofType: "txt")!
txtContent.text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
like image 157
fatihyildizhan Avatar answered Dec 21 '22 01:12

fatihyildizhan


I think this will help you:

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let filePath = (documentsDirectory as NSString).stringByAppendingPathComponent("Logger.txt")
do {
    let content = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)
}catch {/* error handling here */}
like image 21
Muzahid Avatar answered Dec 20 '22 23:12

Muzahid