美文网首页
swift文件存储、读取

swift文件存储、读取

作者: UILabelkell | 来源:发表于2019-07-16 14:55 被阅读0次

    //存储nsdata
    class func savejson(dic:NSData) {
    let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true);
    let libr = filePath[0]+"loging"
    var bol = Bool()
    bol = dic.write(toFile: libr, atomically: true) //存储不同类型 有不同方法
    if bol {
    print("储储成功")
    }else{
    print("储储失败")
    }
    }

    //读取
    class func readloginData(){

        do{
            let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true);
            let libr = filePath[0]+"loging"
            let fileManager = FileManager.default
            let exist = fileManager.fileExists(atPath: libr)
            if exist{
                let  content = fileManager.contents(atPath: libr)
                
                let dat:Data = (content)!
                let dict = String(data: dat, encoding: String.Encoding.utf8)
                let jsonData = dict?.data(using: String.Encoding.utf8, allowLossyConversion: false) ?? Data()
                guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)else{
                    return
                }
                
                print(json)
            }
        }
    }

    相关文章

      网友评论

          本文标题:swift文件存储、读取

          本文链接:https://www.haomeiwen.com/subject/atctlctx.html