ios - attributesOfItem 仅在某些模拟器实例上抛出异常

标签 ios swift

我制作了一个可以在 iPhone X 和 8+ 上运行的程序,但在它之前没有。它引发错误:

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=260 "The file “file.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/mohamedshaaban/Library/Developer/CoreSimulator/Devices/EF98418A-A382-45D4-B1E5-E91709DA2E8D/data/Containers/Data/Application/2362ABE0-3A37-49C5-BEB0-7AC0AF293102/Documents/file.txt, NSUnderlyingError=0x60400005c950 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

当我运行这个函数时会发生这种情况:

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



            }
    }

}

最佳答案

看起来您正在使用模拟器。模拟器中的每个设备都使用 Mac 文件系统上的不同目录。我猜该文件存在于您的 iPhone X sim 使用的目录中,但不存在于您的 iPhone 8 sim 使用的目录中。它很可能与模拟硬件或操作系统无关。

编辑:我之前没有说清楚,应用程序重建/重新启动不会删除这些或任何其他文档,所以如果一个文件曾经在 X sim 上创建,它将保留除非您删除 SIM 卡。

您可以检查 /Users/mohamedshaaban/Library/Developer/CoreSimulator/Devices/ 并比较设备之间的应用程序文档,但是所有这些随机目录名称很烦人。可能更容易只查看您的代码并找出为什么您假设文件存在而实际上不存在。

关于ios - attributesOfItem 仅在某些模拟器实例上抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739404/

相关文章:

ios - 内存写入性能 - GPU CPU 共享内存

objective-c - 自定义 UITableViewCell 不占据单元格的完整边界?

ios - 在 UICollectionView 中,单元格不会位于底部

ios - 将 userLocation 打印到 textLabel

ios - 组件 View 中的 @State 导致奇怪的 UI 状态保留

swift - 如何在 UICollectionView 拖/放过程中删除 'ghost' 单元格,并使移动单元格不透明?

ios - 当滑动太快或连续快速左右滑动时如何跟踪 pageViewController 的索引

ios - 在dismissViewController回调中刷新presentingViewController的UI时意外发现nil

ios - 使用 Realm 存储数据,添加对象清除列表中的对象

iOS 功能和按钮