我正在使用以下代码但我收到错误。
“无法将NSURL类型的值转换为int32”
在这一行:
if let fileHandle = NSFileHandle(fileDescriptor: fileurl, closeOnDealloc: &err).
并收到此错误
“此行没有更多上下文的表达式类型不明确”
if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &err)
代码:
let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
let fileurl = dir.URLByAppendingPathComponent("log.txt")
let string = "\(NSDate())\n"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
var err:NSError?
if let fileHandle = NSFileHandle(fileDescriptor: fileurl, closeOnDealloc: &err) {
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
}
else {
print("Can't open fileHandle \(err)")
}
}
else {
var err:NSError?
if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &err) {
print("Can't write \(err)")
}
}
答案 0 :(得分:4)
你的代码看起来像Swift 1,即便如此,它也不是Swift 1的有效。如果您使用的是Swift 2或更高版本,请尝试以下操作:
let dir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
let fileurl = dir.URLByAppendingPathComponent("log.txt")
let string = "\(NSDate())\n"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
do {
let fileHandle = try NSFileHandle(forWritingToURL: fileurl)
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
} catch {
print("Can't open fileHandle \(error)")
}
} else {
do {
try data.writeToURL(fileurl, options: .DataWritingAtomic)
} catch {
print("Can't write \(error)")
}
}