Created
November 16, 2016 09:05
-
-
Save celian-m/2bf4d9ebbfaf39245d31328fda33ac7f to your computer and use it in GitHub Desktop.
Save WS Call to file [Swift 2.3]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func saveToFile(string : String, url : String, method : String) { | |
guard let dir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last else { return } | |
guard let fileurl = dir.URLByAppendingPathComponent("log.txt") else { return } | |
let dateFormatter = NSDateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZZZZZ" | |
let string = dateFormatter.stringFromDate(NSDate()) + " [" + method + "] " + url + "\n" + string + "\n" | |
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! | |
if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) { | |
if let fileHandle = try? NSFileHandle(forWritingToURL : fileurl) { | |
fileHandle.seekToEndOfFile() | |
fileHandle.writeData(data) | |
fileHandle.closeFile() | |
} | |
else { | |
print("Can't open fileHandle ") | |
} | |
} | |
else { | |
do { | |
try data.writeToURL(fileurl, options: .DataWritingAtomic) | |
}catch { | |
print("Can't write \(error)") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment