我制作的程序适用于iPhone X和8+,但之前没有任何东西。它引发了一个错误:
线程1:致命错误:'尝试!'表达式意外地引发了一个错误: 错误域= NSCocoaErrorDomain代码= 260"文件“file.txt”不能 因为没有这样的文件而被打开。" 的UserInfo = {NSFilePath = /用户/ mohamedshaaban /库/开发商/ CoreSimulator /设备/ EF98418A-A382-45D4-B1E5-E91709DA2E8D /数据/容器/数据/应用/ 2362ABE0-3A37-49C5-BEB0-7AC0AF293102 /文档/文件。文本, NSUnderlyingError = 0x60400005c950 {错误域= NSPOSIXErrorDomain 代码= 2"没有这样的文件或目录"}}
当我运行此功能时会发生这种情况:
let attributes = try! FileManager.default.attributesOfItem(atPath:fileURL.path)
let fileSize = attributes[.size] as! NSNumber
任何想法为什么?
import UIKit
import SwiftECP
import XCGLogger
class ViewController: UIViewController {
@IBOutlet var UsernameField: UITextField!
@IBOutlet var passwordField: UITextField!
var file = "file"
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10, *) {
// Disables the password autoFill accessory view.
UsernameField.textContentType = UITextContentType("")
passwordField.textContentType = UITextContentType("")
}
}
@IBAction func _Login(_ sender: Any) {
gotourl()
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent("file").appendingPathExtension("txt")
var readString = ""
do {
// Read the file contents
readString = try String(contentsOf: fileURL)
print ( "Reading from file \(readString)")
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
let attributes = try! FileManager.default.attributesOfItem(atPath:fileURL.path)
let fileSize = attributes[.size] as! NSNumber
print ("Here is file \(fileSize)")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
if fileSize != 0{
self.performSegue(withIdentifier: "gotowelcome", sender: self)
}
else
{
let alert = UIAlertController(title: "Login error", message: "Wrong Username or password.", preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.destructive, handler: { action in
self.UsernameField.text=""
self.passwordField.text=""
}))
// show the alert
self.present(alert, animated: true, completion: nil)
// Do any additional setup after loading the view.
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func checkfilesize(){
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// change 2 to desired number of seconds
// Your code with delay
}
}
func gotourl(){
let username1: String = UsernameField.text!
let password1: String = passwordField.text!
let protectedURL = URL(
string: "https://itsapps.odu.edu/auth/getInfo.php"
)!
let logger = XCGLogger()
logger.setup(level: .debug)
ECPLogin(
protectedURL: protectedURL,
username: username1,
password: password1,
logger: logger
).start { event in
switch event {
case let .value( body) :
// If the request was successful, the protected resource will
// be available in 'body'. Make sure to implement a mechanism to
// detect authorization timeouts.
print("Response body: \(body)")
//this is the file. we will write to and read from it
let text = "\(body)" //just a text
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent("file").appendingPathExtension("txt")
//print("FilePath: \(fileURL.path)")
do {
// Write to the file
try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
print ("here is what is in file \(fileURL)")
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
// The Shibboleth auth cookie is now stored in the sharedHTTPCookieStorage.
// Attach this cookie to subsequent requests to protected resources.
// You can access the cookie with the following code:
if let cookies = HTTPCookieStorage.shared.cookies {
let shibCookie = cookies.filter { (cookie: HTTPCookie) in
cookie.name.range(of: "shibsession") != nil
}[0]
print(shibCookie)
}
case let .failed(error):
// This is an AnyError that wraps the error thrown.
// This can help diagnose problems with your SP, your IdP, or even this library :)
switch error.cause {
case let ecpError as ECPError:
// Error with ECP
// User-friendly error message
print(ecpError.userMessage)
// Technical/debug error message
print(ecpError.description)
case let alamofireRACError as AlamofireRACError:
// Error with the networking layer
print(alamofireRACError.description)
default:
print("Unknown error!")
print(error)
}
default:
break
}
}
}
}
答案 0 :(得分:1)
看起来你正在使用模拟器。模拟器中的每个设备都使用Mac文件系统上的不同目录。我猜这个文件存在于你的iPhone X sim使用的目录中,但不是你的iPhone 8 sim使用的目录。它很可能与模拟硬件或操作系统无关。
编辑:我之前没有说清楚应用程序重建/重新启动不删除这些或任何其他文档,因此如果在X sim上创建了 文件,它将保留除非你擦拭SIM卡。
您可以检查/Users/mohamedshaaban/Library/Developer/CoreSimulator/Devices/
并比较设备之间的应用文档,但这对所有随机目录名称都很烦人。可能更容易查看您的代码并找出为什么您假设文件存在而不存在。