"dataWithContentsOfMappedFile"在iOS 8.0中已弃用。

4
我使用以下代码从JSON文件中检索数据。
let jsonData = try NSData.dataWithContentsOfMappedFile("/Users/User/Desktop/Employee.json")

我遇到了以下错误。
dataWithContentsOfMappedFile was deprecated in iOS 8.0: Use +dataWithContentsOfURL:options:error: and NSDataReadingMappedIfSafe or NSDataReadingMappedAlways instead

有没有人可以告诉我替代方案?

1
你没有提供解决方案吗?尝试使用+dataWithContentsOfURL:options:error:和NSDataReadingMappedIfSafe或NSDataReadingMappedAlways。你试过了吗? - NeverHopeless
尝试这个:https://dev59.com/hW435IYBdhLWcg3wpxyx - Irfan Gul
@NeverHopeless 我不想从任何URL使用它。文件在我的本地。 - RStack
1
实际上,在头文件中就在那里。所有过时的方法都在头文件中有一行告诉你应该使用什么代替。 - gnasher729
1个回答

4

请尝试以下方法:

如果要从本地路径获取,请使用contentsOfFile,否则请使用contentsOfURL

 let contents: NSData?
    do {
        contents = try NSData(contentsOfFile: "/Users/User/Desktop/Employee.json", options: NSDataReadingOptions.DataReadingMappedAlways)
    } catch _ {
        contents = nil
    }

    print(contents)

如果您只想访问contentsOfFile,请使用以下行:

    let contents   =  NSData(contentsOfFile:"/Users/User/Desktop/Employee.json")
     print(contents)

我遇到了这个错误/Users/Rini/Documents/workspace/MyAppSwift/MyAppSwift/ViewController.swift:20:98: 表达式的类型在没有更多上下文的情况下是模棱两可的 - RStack
我只能使用这个代码: let jsonData = try NSData(contentsOfFile: "/Users/User/Desktop/Employee.json") 但是我不知道下一步该怎么做... - RStack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接