gpt4 book ai didi

ios - 快速解析来自rest api的xml数据

转载 作者:行者123 更新时间:2023-11-30 13:17:38 31 4
gpt4 key购买 nike

我正在尝试从rest api解析xml数据,数据被解析并存储在名为NewslettersParser的类中的数组帖子中,但我无法将其存储在另一个名为MyTableViewController的类中>,这是我的代码:

NewslettersParser.swift:

import Foundation

private var url = NSURL(string: "http://www.iaa.edu.jo/load/iaa/newsletters")

class NewslettersParser: NSObject, NSXMLParserDelegate{

var parser : NSXMLParser! = NSXMLParser(contentsOfURL: url!)
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var postFile:String = ""
var postDate:String = ""
var posts: [Newsletters] = []
var counter: Int = 0
var pageNumber: Int = 1
var news: Newsletters = Newsletters()
let defaults = NSUserDefaults.standardUserDefaults()



func getData() {
let postEndpoint: String = "http://www.iaa.edu.jo/load/iaa/newsletters"
let url = NSURL(string: postEndpoint)!
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let paramString = "page=\(pageNumber)"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
let newStr = String(data: data!, encoding: NSUTF8StringEncoding)
print(newStr)

self.parser = NSXMLParser(data: data!)
self.parser.delegate = self
self.parser.parse()

let success:Bool = self.parser.parse()

if success {
print("parse success!")

} else {
//error
}


}).resume()


}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName
if(elementName=="item" || elementName=="date" || elementName=="file"){
if(elementName=="item"){
passName=true
}
passData=true
}
}

func parser(parser: NSXMLParser, foundCharacters string: String) {
if(passData){

if currentElement=="date"{
postDate = string
}
else if currentElement=="file"{
postFile = string
}
}
}

// func parserDidEndDocument(parser: NSXMLParser){
// news.fetch(posts)
//}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement=""
let post: Newsletters = Newsletters()

if(elementName=="item" || elementName=="date" || elementName=="file"){

if(elementName=="item"){
passName=false
post.date = postDate
post.file = postFile
posts.append(post)
counter += 1
if(counter == 10){
pageNumber += 1
counter = 0
self.getData()
}
}
}
if(posts.count == 23){
news.data = posts
}
//self.myTable.reloadData()
}


func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog("failure error: %@", parseError)
}


}

这是 MyTableViewController:

import UIKit
import SDWebImage

class MyTableTableViewController: UITableViewController {

@IBOutlet var myTable: UITableView!


var newsletters: [Newsletters] = []
var news: Newsletters = Newsletters()

let Nparse: NewslettersParser = NewslettersParser()

override func viewDidLoad() {
super.viewDidLoad()
//
Nparse.getData()
newsletters = news.data
self.myTable.reloadData()

}

和 Newsletters.swift:

class Newsletters{
var file: String = String()
var date: String = String()
var data: [Newsletters] = []
let Nparse: NewslettersParser = NewslettersParser()
}

提前谢谢您。

最佳答案

委托(delegate)模式非常适合这种情况。您可以在 Controller 解析完成后使用委托(delegate)方法。

委托(delegate)协议(protocol)

protocol NewslettersParserDelegate: class {
func finishedParsing()
}

**具有委托(delegate)能力的 NewslettersParser.swift **

    import Foundation

private var url = NSURL(string: "http://www.iaa.edu.jo/load/iaa/newsletters")

class NewslettersParser: NSObject, NSXMLParserDelegate{

var parser : NSXMLParser! = NSXMLParser(contentsOfURL: url!)
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var postFile:String = ""
var postDate:String = ""
var posts: [Newsletters] = []
var counter: Int = 0
var pageNumber: Int = 1
var news: Newsletters = Newsletters()
let defaults = NSUserDefaults.standardUserDefaults()

// delegate property
weak var newslettersParserDelegate: NewslettersParserDelegate!



func getData() {
let postEndpoint: String = "http://www.iaa.edu.jo/load/iaa/newsletters"
let url = NSURL(string: postEndpoint)!
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let paramString = "page=\(pageNumber)"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
let newStr = String(data: data!, encoding: NSUTF8StringEncoding)
print(newStr)

self.parser = NSXMLParser(data: data!)
self.parser.delegate = self
self.parser.parse()

let success:Bool = self.parser.parse()

if success {
print("parse success!")

} else {
//error
}


}).resume()


}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName
if(elementName=="item" || elementName=="date" || elementName=="file"){
if(elementName=="item"){
passName=true
}
passData=true
}
}

func parser(parser: NSXMLParser, foundCharacters string: String) {
if(passData){

if currentElement=="date"{
postDate = string
}
else if currentElement=="file"{
postFile = string
}
}
}

// func parserDidEndDocument(parser: NSXMLParser){
// news.fetch(posts)
//}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement=""
let post: Newsletters = Newsletters()

if(elementName=="item" || elementName=="date" || elementName=="file"){

if(elementName=="item"){
passName=false
post.date = postDate
post.file = postFile
posts.append(post)
counter += 1
if(counter == 10){
pageNumber += 1
counter = 0
self.getData()
}
}
}
if(posts.count == 23){
news.data = posts
}
//self.myTable.reloadData() instead of this you can now call
newslettersParserDelegate.finishedParsing()
}


func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog("failure error: %@", parseError)
}


}

现在在您的 MyTableViewController 中,您可以确认委托(delegate)并使用该方法

import UIKit
import SDWebImage

class MyTableTableViewController: UITableViewController, NewslettersParserDelegate {

@IBOutlet var myTable: UITableView!

var newsletters: [Newsletters] = []
var news: Newsletters = Newsletters()

let Nparse: NewslettersParser = NewslettersParser()

override func viewDidLoad() {
super.viewDidLoad()
//
Nparse.getData()
Nparse.newslettersParserDelegate = self

newsletters = news.data
self.myTable.reloadData()

}

func finishedParsing(){
// reload data upon finishing parsing
}


}

关于ios - 快速解析来自rest api的xml数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069980/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com