使用 swift 5 从远程读取 json 内容并在 Xcode 的主界面上打印
Posted
技术标签:
【中文标题】使用 swift 5 从远程读取 json 内容并在 Xcode 的主界面上打印【英文标题】:Read json content from remote and printing on main interface in Xcode with swift 5 【发布时间】:2019-08-23 09:09:00 【问题描述】:从远程 url 读取 json 内容并在 ios 模拟器的主界面上打印时出错。
MBP13"2016 && Mojave 10.14.6 && xcode 10.3(10G8) && swift 5
这是代码示例。我从“https://www.simplifiedios.net/swift-json-tutorial/”做了一点改动
import UIKit
class ViewController: UIViewController
//the json file url
let URL_POSTS = "https://demo.ghost.io/ghost/api/v2/content/posts/?key=22444f78447824223cefc48062";
//A string array to save all the names
var nameArray = [String]()
//the label we create
@IBOutlet weak var labelTest: UILabel!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//calling the function that will fetch the json
getJsonFromUrl();
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
//this function is fetching the json from URL
func getJsonFromUrl()
//creating a NSURL
let url = NSURL(string: URL_POSTS)
//fetching the data from the url
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: (data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
//printing the json in console
print(jsonObj.value(forKey: "posts")!)
//getting the companies tag array from json and converting it to NSArray
if let heroeArray = jsonObj.value(forKey: "posts") as? NSArray
//looping through all the elements
for heroe in heroeArray
//converting the element to a dictionary
if let heroeDict = heroe as? NSDictionary
//getting the name from the dictionary
if let name = heroeDict.value(forKey: "name")
//adding the name to the array
self.nameArray.append((name as? String)!)
OperationQueue.main.addOperation(
//calling another function after fetching the json
//it will show the names to label
self.showNames()
)
).resume()
func showNames()
//looing through all the elements of the array
for name in nameArray
//appending the names to label
labelTest.text = labelTest.text! + name + "\n";
从上面的结果来看,我在从远程 url 获取 json 时在控制台中找到了内容结果似乎没问题,但在 iOS 模拟器的主界面上没有显示任何内容。
json result in console
main interface nothing show up in IOS Simulator
【问题讨论】:
【参考方案1】:我在使用 JSON 键和 NSDictionary 时遇到了某种问题。对我有用的只是使用 Decodable 协议。我建议使用这个新的 API 进行解析,而不是 JSONSerialization。
这里有一些不错的读物:
https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375 https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1
【讨论】:
以上是关于使用 swift 5 从远程读取 json 内容并在 Xcode 的主界面上打印的主要内容,如果未能解决你的问题,请参考以下文章
NSMutableArray true 转换为 json 输出并在 Swift 3 中使用 Alamofire 将其发布到远程
Swift 3 - 如何从包含字符串的索引中读取 json 输出
尝试从 swift 2 中的 JSON 文件中读取重载错误出现