繁体   English   中英

attributeOfItem仅在某些模拟器实例上引发异常

[英]attributesOfItem throws exception only on some simulator instance

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

线程1:致命错误:“尝试!” 表达式意外引发错误:Error Domain = NSCocoaErrorDomain代码= 260“由于没有这样的文件,因此无法打开文件“ file.txt”。 的UserInfo = {NSFilePath = /用户/ mohamedshaaban /库/开发商/ CoreSimulator /设备/ EF98418A-A382-45D4-B1E5-E91709DA2E8D /数据/容器/数据/应用/ 2362ABE0-3A37-49C5-BEB0-7AC0AF293102 /文档/文件。 txt,NSUnderlyingError = 0x60400005c950 {Error Domain = 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



            }
    }

}

}

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

编辑:在应用程序重建/重新发布之前,我没有明确表示不会删除这些文件或任何其他文档,因此,如果曾经在X sim卡上创建过文件,除非您擦除sim卡,否则它将一直存在。

您可以检查/Users/mohamedshaaban/Library/Developer/CoreSimulator/Devices/并比较设备之间的应用程序文档,但是所有这些随机目录名都令人讨厌。 仅仅查看代码并找出为什么假设文件不存在的原因可能更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM