无法从URL解析XML确实是API

时间:2016-11-13 15:35:21

标签: ios xml api parsing

好吧,我正在使用这个库来解析xml:SwiftyXMLParser,但遗憾的是无法从IOS中的响应中获取结果数组,但我可以在浏览器see this linksample of respond上看到它们!

这是我的操作:

URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

    if error != nil {
        print(error)
        return
    }
    if let data = data {
        let xml = XML.parse(data)
        print(xml)
        //tried xml["results"]["0"] also didn't work
    }

}).resume()

这是我在IOS中的输出:

<response version="2">
<query>ios</query>
<location>austin, tx</location>
<clickedCategories/>
<paginationPayload/>
<radius>25</radius>
<dupefilter>true</dupefilter>
<highlight>false</highlight>
<start>1</start>
<end>10</end>
<pageNumber>0</pageNumber>
<totalresults>315</totalresults>
<results>
//This is array but No results!!
<\results>

所有人都知道为什么?怎么样?

谢谢。

我对json的尝试:

让我确实API =“api.indeed.com/ads/apisearch?publisher=4935138002921571&q=(searchTerm)&format=json&l=%2C+tx&sort=&radius=50&st=& ; JT =安培;开始=&安培;限制= 10安培;清爽=安培;过滤器=安培;经纬度= 1&安培; CO =&安培; CHNL =安培; USERIP = 1.2.3.4&安培; v = 2"

    let googleYoutubeAPIUrl = URL(string: indeedAPI.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)

    let request:URLRequest = URLRequest(url: googleYoutubeAPIUrl!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 5.0)

    OperationQueue.main.cancelAllOperations()
    let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in

        if let _ = error {
            print(error.debugDescription)
            return
        }

        if let data = data {
            completion(JSON(data: data))
        } else { print("data nil"); return }

    })
    task.resume()

{
  "paginationPayload" : "",
  "location" : "%2C tx",
  "dupefilter" : true,
  "results" : [
// also no results
  ],
  "totalResults" : 0,
  "version" : 2,
  "end" : 0,
  "pageNumber" : 0,
  "start" : 0,
  "query" : "ios developer",
  "highlight" : true
}

1 个答案:

答案 0 :(得分:0)

如果您要查找result条目,可以执行以下操作:

let xml = XML.parse(data)

guard xml.error == nil else {
    print("\(xml.error!)")
    return
}

let results = xml["response", "results"]

guard results.error == nil && results["result"].error == nil else {
    print("no results")
    return
}

for result in results["result"] {
    if let jobtitle = result["jobtitle"].text {
        print("\(jobtitle)")
    }
}