如何从 url 获取 web 服务数据?
Posted
技术标签:
【中文标题】如何从 url 获取 web 服务数据?【英文标题】:how to get web services data from url? 【发布时间】:2017-08-02 06:18:42 【问题描述】:在这个网络服务中,我需要获取数据并按照image 中的说明显示网址是
let url = "http://www.json-generator.com/api/json/get/cwqUAMjKGa?indent=2"
var detailsArray :[[String: AnyObject]] = []
var titleName = [String]()
var productName = [String]()
var children = [String]()
var childrenArray :[[String: AnyObject]] = []
var productsArray :[[String:AnyObject]] = []
var name = [String]()
func downloadJsonWithURL()
let url = NSURL(string: self.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
self.detailsArray = (jsonObj!.value(forKey: "data") as? [[String: AnyObject]])!
print(self.detailsArray)
for item in self.detailsArray
if let detailDict = item as? NSDictionary
if let name = detailDict.value(forKey: "name")
self.titleName.append(name as! String)
print(self.productName)
self.childrenArray = (detailDict.value(forKey: "children") as? [[String : AnyObject]])!
print(self.childrenArray)
OperationQueue.main.addOperation(
print(self.productName)
print(self.titleName)
print(self.name)
)
).resume()
【问题讨论】:
您收到网络服务的响应了吗? 我能够得到,但是否可以将它传递给表格视图,就像我在上面的图片@KKRocks 中显示的那样 只有一些我得到的数据,后来它会崩溃@KKRocks 你能告诉我你的应用在哪里崩溃了吗? 这里崩溃了i.stack.imgur.com/8OKOX.png 【参考方案1】:试试这个:
self.detailsArray = (jsonObj.value(forKey: "data") as? [[String: AnyObject]])!
print(self.detailsArray)
for item in self.detailsArray
if let detailDict = item as? [String : AnyObject]
if let name = detailDict["name"]
self.titleName.append(name as! String)
print(self.productName)
if let dictChildren = detailDict["children"]
if ((dictChildren as? [Any]) != nil)
self.childrenArray = dictChildren as! [[String : AnyObject]];
print(self.childrenArray)
【讨论】:
我得到对象成功。 @vamsi 试试我的答案。 在子数组中它在 nslog @KKRocks 中显示为空 是的,因为作为响应,儿童数组不会出现 那么如何在子数组@KKRocks 中获取数据【参考方案2】:我已经尝试了您的代码,并且以下解决方案正在运行。
func downloadJsonWithURL()
let url = NSURL(string: self.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
self.detailsArray = (jsonObj!.value(forKey: "data") as? [[String: AnyObject]])!
print(self.detailsArray)
for item in self.detailsArray
if let detailDict = item as? [String:AnyObject]
if let name = detailDict["name"]
self.titleName.append(name as! String)
print(self.productName)
self.childrenArray = (detailDict["children"]as? [[String : AnyObject]])!
print(self.childrenArray)
OperationQueue.main.addOperation(
print(self.productName)
print(self.titleName)
print(self.name)
)
).resume()
【讨论】:
以上是关于如何从 url 获取 web 服务数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Flutter Web 中的 google url 获取数据