从 Swift ( iOS) 进行 HTTP 调用(GET、POST 等)
Making HTTP calls ( GET, POST etc ) from Swift ( iOS)
我是 swift 编程语言的新手,我正在尝试寻找一种方法从 swift 进行 HTTP/API 调用。我知道如何在 Javascript 中准确地做到这一点,因为我之前已经使用过很多次。但我似乎无法弄清楚 swift.
我在网上找到了这段代码,并且我一直在 XCODE Playground 中测试它。但它正在返回 "nil"
代码如下:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground // add this in
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
var str = "Hello, playground"
// create a session object
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// make a network request for a URL, in this case our endpoint
session.dataTaskWithURL(NSURL(string: "http://echo.jsontest.com/key/value/one/two")!,
completionHandler: { (taskData, taskResponse, taskError) -> Void in
// create an NSArray with the JSON response data
var jsonReadError:NSError?
let jsonArray = NSJSONSerialization.JSONObjectWithData(
taskData, options: nil, error: &jsonReadError) as! [AnyObject]
}).resume()
谁能告诉我我做错了什么。谢谢你。
如果我犯了错误,请告诉我,或者如果您需要更多信息,请告诉我。
试试这个:
let jsonResult = NSJSONSerialization.JSONObjectWithData(taskData, options: NSJSONReadingOptions.MutableContainers, error: &jsonReadError) as! NSDictionary
我是 swift 编程语言的新手,我正在尝试寻找一种方法从 swift 进行 HTTP/API 调用。我知道如何在 Javascript 中准确地做到这一点,因为我之前已经使用过很多次。但我似乎无法弄清楚 swift.
我在网上找到了这段代码,并且我一直在 XCODE Playground 中测试它。但它正在返回 "nil"
代码如下:
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground // add this in
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
var str = "Hello, playground"
// create a session object
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
// make a network request for a URL, in this case our endpoint
session.dataTaskWithURL(NSURL(string: "http://echo.jsontest.com/key/value/one/two")!,
completionHandler: { (taskData, taskResponse, taskError) -> Void in
// create an NSArray with the JSON response data
var jsonReadError:NSError?
let jsonArray = NSJSONSerialization.JSONObjectWithData(
taskData, options: nil, error: &jsonReadError) as! [AnyObject]
}).resume()
谁能告诉我我做错了什么。谢谢你。 如果我犯了错误,请告诉我,或者如果您需要更多信息,请告诉我。
试试这个:
let jsonResult = NSJSONSerialization.JSONObjectWithData(taskData, options: NSJSONReadingOptions.MutableContainers, error: &jsonReadError) as! NSDictionary