URLSession参数必须有效

时间:2018-04-10 10:44:15

标签: ios swift urlsession

这是我要求的网址

  

https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq

如果您在浏览器上运行它,它可以正常工作并提供JSON响应。但是,在运行以下代码时,我在catch块中收到此错误: URLSession参数必须有效

let callURL = URL.init(string: urlString)    // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
request.httpMethod = HTTPMethod_Get    
let dataTask = urlSession.dataTask(with: request) { (data,response,error) in
        if error != nil{
            completion(nil)
            return
        }
        do {
            if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
                print("Result",resultJson)
                if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
                    print("News",news)
                    completion(news)
                    return
                }
            }
        } catch {
            print("Error -> \(error)")
        }
    }

dataTask.resume()

3 个答案:

答案 0 :(得分:3)

我不确定你的代码有什么问题,但我已经在操场上测试了你的上述代码我在下面得到的消息是代码

import Foundation
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL.init(string: urlString)    // urlString is the above url
var request = URLRequest.init(url: callURL!)
request.addValue("Content-Type", forHTTPHeaderField: "application/json")
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in

    let res = response as! HTTPURLResponse
    print(res)
    if error != nil{
        print(error!)
        return
    }
    do {
        if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
            print("Result",resultJson)
            if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
                print("News",news)

                return
            }
        }
    } catch {
        print("Error -> \(error)")
    }
}

dataTask.resume()

答案 1 :(得分:1)

这对我有用

    let callURL = URL.init(string: "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq")    // urlString is the above url
    var request = URLRequest.init(url: callURL!)
     request.httpMethod = HTTPMethod.get.rawValue
    let dataTask = URLSession.shared.dataTask(with: request) { (data,response,error) in
        if error != nil{

           print(error)
        }
        do {
            if let resultJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary{
                print("Result",resultJson)
                if let news = resultJson.value(forKeyPath: "articles") as? [NSDictionary]{
                    print("News",news)

                    return
                }
            }
        } catch {
            print("Error -> \(error)")
        }
    }

    dataTask.resume()

答案 2 :(得分:1)

您不需要为GET请求提供URLRequest,这是默认设置,只需传递URL

这有效,但键articles

没有价值
let urlString = "https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.theverge.com%2Frss%2Findex.xml&api_key=u3vl3sxdva2cch7jjyrnynvwlhjycjrizhcsgmmq"
let callURL = URL(string: urlString)!
let dataTask = URLSession.shared.dataTask(with: callURL) { (data,response,error) in
    if error != nil { return }
    do {
        if let resultJson = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
            print("Result",resultJson)
//            if let news = resultJson["articles"] as? [[String:Any]] {
//                print("News",news.count)
//                return
//            }
        }
    } catch {
        print("Error -> \(error)")
    }
}
dataTask.resume()

并且 - 一如既往 - 在Swift 中不使用NSDictionaryvalueForKey,如果根对象是集合类型,则.allowFragments毫无意义。