我正在将以下卷曲转换为Swift
但不幸的是,在PlayGround上运行时出现以下错误:
Optional(["errors": <__NSSingleObjectArrayI 0x60c00000da70>({
code = invalid;
field = q;
message = "\"`date\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.";
resource = Search;
}), "documentation_url": https://developer.github.com/v3/search/,
"message": Validation Failed])
这是以下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()
答案 0 :(得分:0)
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")
]