如何使用 Swift 将 NSURL 转换为 JSON
How to convert NSURL to JSON using Swift
我试图从图 url(在 JSON 中)获取响应并将其保存在变量中,但问题是我不知道语法要做到这一点,我无法在网上找到它,我所拥有的是这一行,当我在浏览器中输入它时,它正在为我提供所需的信息:
let usercontexturl: NSURL = NSURL(string: "https://graph.facebook.com/\(facebookContext)/mutual_friends?access_token=\(access_token)")!
而我想做的是将url的内容保存在一个变量中,我该怎么做?
更新:
感谢@JHZ 的回答我弄明白了,我以前这样做的代码是这样的:
let myrequest: NSURLRequest = NSURLRequest(URL: usercontexturl)
let mysession = NSURLSession.sharedSession()
let task = mysession.dataTaskWithRequest(myrequest) { data, response, error in
do {
let jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(jsonresult)
} catch {
print(error)
}
}
task.resume()
您正在寻找 NSURLRequest
、NSURLSession
和 NSJSONSerialization
。
你会想要 this initializer.
您应该将其输入 this NSURLSession
方法。
从完成处理程序中,您可以调用 this method 来获取 JSON。
感谢@JHZ,我可以让它工作,我以前这样做的代码是这样的:
let myrequest: NSURLRequest = NSURLRequest(URL: usercontexturl)
let mysession = NSURLSession.sharedSession()
let task = mysession.dataTaskWithRequest(myrequest) { data, response, error in
do {
let jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(jsonresult)
} catch {
print(error)
}
}
task.resume()
我试图从图 url(在 JSON 中)获取响应并将其保存在变量中,但问题是我不知道语法要做到这一点,我无法在网上找到它,我所拥有的是这一行,当我在浏览器中输入它时,它正在为我提供所需的信息:
let usercontexturl: NSURL = NSURL(string: "https://graph.facebook.com/\(facebookContext)/mutual_friends?access_token=\(access_token)")!
而我想做的是将url的内容保存在一个变量中,我该怎么做?
更新:
感谢@JHZ 的回答我弄明白了,我以前这样做的代码是这样的:
let myrequest: NSURLRequest = NSURLRequest(URL: usercontexturl)
let mysession = NSURLSession.sharedSession()
let task = mysession.dataTaskWithRequest(myrequest) { data, response, error in
do {
let jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(jsonresult)
} catch {
print(error)
}
}
task.resume()
您正在寻找 NSURLRequest
、NSURLSession
和 NSJSONSerialization
。
你会想要 this initializer.
您应该将其输入 this NSURLSession
方法。
从完成处理程序中,您可以调用 this method 来获取 JSON。
感谢@JHZ,我可以让它工作,我以前这样做的代码是这样的:
let myrequest: NSURLRequest = NSURLRequest(URL: usercontexturl)
let mysession = NSURLSession.sharedSession()
let task = mysession.dataTaskWithRequest(myrequest) { data, response, error in
do {
let jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(jsonresult)
} catch {
print(error)
}
}
task.resume()