OStack程序员社区-中国程序员成长平台

标题: ios - 在 Swift 4.0 中获取上个月趋势存储库时出错 - Github API [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:16
标题: ios - 在 Swift 4.0 中获取上个月趋势存储库时出错 - Github API

我正在将以下 curl 转换为 Swift 但不幸的是,在 PlayGround 上运行时出现以下错误:

可选([“错误”:<__NSSingleObjectArrayI 0x60c00000da70>({ 代码=无效; 场 = q; message = "\"`date\"不是可识别的日期/时间格式。请提供 ISO 8601 日期/时间值,例如 YYYY-MM-DD。"; 资源=搜索; }), "documentation_url": https://developer.github.com/v3/search/, “消息”:验证失败])

这是下面的cUrl,。它在终端执行时确实有效。

curl -G https://api.github.com/search/repositories --data-urlencode "q=created:>`date -v-1m '+%Y-%m-%d'`"--data- urlencode "sort=stars"--data-urlencode "order=desc"-H "Accept: application/json"

这是我的要求:

    let sessionConfig = URLSessionConfiguration.default

    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    guard var urlComponent = URLComponents(string: "https://api.github.com/search/repositories") else { return }
    let items = [
        URLQueryItem(name: "q", value: "created:>`date -v-1m '+%Y-%m-%d'`"),
        URLQueryItem(name: "sort", value: "stars"),
        URLQueryItem(name: "order", value: "desc")
    ]

    urlComponent.queryItems = items
    guard let url = urlComponent.url else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"


    // Headers
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

    // Form URL-Encoded Body


    /* Start a new Task */
    let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
        if (error == nil) {
            // Success
            let statusCode = (response as! HTTPURLResponse).statusCode
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
                print(json)
            } catch {
                print(error)
            }
        }
        else {
            // Failure
            print("URL Session Task Failed: %@", error!.localizedDescription);
        }
    })
    task.resume()
    session.finishTasksAndInvalidate()



Best Answer-推荐答案


cURL 在终端上运行一个脚本,因此,它将日期 -1m 作为 q 参数传递。例如,如果这个答案的日期是 2017-11-13,那么 date -v-1m '+%Y-%m-%d' 将是 >2017-10-13

let items = [
    URLQueryItem(name: "q", value: "created:>2017-10-13"),
    URLQueryItem(name: "sort", value: "stars"),
    URLQueryItem(name: "order", value: "desc")
]

关于ios - 在 Swift 4.0 中获取上个月趋势存储库时出错 - Github API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47254710/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4