有人可以找到错误并验证我的 Swift NSURLSession 代码吗?
Can someone find the error and verify my Swift NSURLSession code?
我正在使用 Swift 编写我的第一个基本 IOS 应用程序,它将轮询 Proliphix IP 恒温器并显示温度。我已经使用 Paw 将 HTTP Post 转换为 NSURLSession,但是当我将它加载到 Xcode Playground 时,转换后的代码似乎有 3 个语法错误。
我现在的目标是让它在 Playground 中运行,但最终会在我的 App 代码中使用它。有人可以在您自己的 Xcode Playground 中加载此代码并修复错误并使其正常工作吗? URL 是恒温器的 public IP 地址,如果工作正常,它将轮询恒温器和 return OID4.3.2.3 的值和 = 类似 772&(当前为 77.2度)。
class MyRequestController {
func sendRequest() {
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
/* Create session, and optionally set a NSURLSessionDelegate. */
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
/* Create the Request:
My API (POST http://my-thermostat.dyndns.org:8083/get)
*/
var URL = NSURL(string: "http://my-thermostat.dyndns.org:8083/get")
let request = NSMutableURLRequest(URL: URL!)
request.HTTPMethod = "POST"
// Headers
request.addValue("Basic dXNlcjpwYXNzd29yZA==", forHTTPHeaderField: "Authorization")
// Form URL-Encoded Body
let bodyParameters = [
"OID4.3.2.3": "",
]
let bodyString = self.stringFromQueryParameters(bodyParameters)
request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
}
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
string will be @"day=Tuesday&month=January".
@param queryParameters The input dictionary.
@return The created parameters string.
*/
func stringFromQueryParameters(queryParameters : Dictionary<String, String>) -> String {
var parts: [String] = []
for (name, value) in queryParameters {
var part = NSString(format: "%@=%@",
name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!,
value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
parts.append(part)
}
return "&".join(parts)
}
/**
Creates a new URL by adding the given query parameters.
@param URL The input URL.
@param queryParameters The query parameter dictionary to add.
@return A new NSURL.
*/
func NSURLByAppendingQueryParameters(URL : NSURL!, queryParameters : Dictionary<String, String>) -> NSURL {
let URLString : NSString = NSString(format: "%@?%@", URL.absoluteString!, self.stringFromQueryParameters(queryParameters))
return NSURL(string: URLString)!
}
}
我想我需要在 Playground 中使用上面这段代码才能正常工作吗?
import Foundation
import XCPlayground
最后,我用来转换的 HTTP Post 来自下面,Paw 将其转换为上面的 NSURLSession。
POST /get HTTP/1.1
Authorization: Basic dXNlcjpwYXNzd29yZA==
Content-Type: application/x-www-form-urlencoded
Host: my-thermostat.dyndns.org:8083
Connection: close
User-Agent: Paw/2.2.2 (Macintosh; OS X/10.10.4) GCDHTTPRequest
Content-Length: 11
OID4.3.2.3=
感谢您的帮助!
如果我使用您的代码创建游乐场,我会遇到三个错误。
函数 sendRequest()
中的一个,您必须更改此行:
let statusCode = (response as NSHTTPURLResponse).statusCode
到
let statusCode = (response as! NSHTTPURLResponse).statusCode
(as!
而不是 as
)
函数 stringFromQueryParameters
中的一个,您必须在其中更改以下行
parts.append(part)
至
parts.append(part as String)
(添加 as String
)
还有函数 NSURLByAppendingQueryParameters
中的一个,您必须在其中更改:
return NSURL(string: URLString)!
对此:
return NSURL(string: URLString as String)!
(添加 as String
)
然后编译器似乎很满意......至少在我的机器上 :-)
是的,您需要导入 Foundation 和 XCPlayground,正如您已经知道的那样。
此外,如果您需要进行异步调用...就像这里的情况一样,您需要在代码顶部使用此方法:
XCPSetExecutionShouldContinueIndefinitely()
(您可以阅读更多相关信息 here)
最后,要实际查看您的代码 运行,您可以将其添加到代码底部,在 class 定义之后:
let requestController = MyRequestController()
requestController.sendRequest()
这里是完整的代码
import Foundation
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
class MyRequestController {
func sendRequest() {
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
/* Create session, and optionally set a NSURLSessionDelegate. */
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
/* Create the Request:
My API (POST http://my-thermostat.dyndns.org:8083/get)
*/
var URL = NSURL(string: "http://my-thermostat.dyndns.org:8083/get")
let request = NSMutableURLRequest(URL: URL!)
request.HTTPMethod = "POST"
// Headers
request.addValue("Basic dXNlcjpwYXNzd29yZA==", forHTTPHeaderField: "Authorization")
// Form URL-Encoded Body
let bodyParameters = [
"OID4.3.2.3": "",
]
let bodyString = self.stringFromQueryParameters(bodyParameters)
request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as! NSHTTPURLResponse).statusCode
println("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
}
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
string will be @"day=Tuesday&month=January".
@param queryParameters The input dictionary.
@return The created parameters string.
*/
func stringFromQueryParameters(queryParameters : Dictionary<String, String>) -> String {
var parts: [String] = []
for (name, value) in queryParameters {
var part = NSString(format: "%@=%@",
name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!,
value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
parts.append(part as String)
}
return "&".join(parts)
}
/**
Creates a new URL by adding the given query parameters.
@param URL The input URL.
@param queryParameters The query parameter dictionary to add.
@return A new NSURL.
*/
func NSURLByAppendingQueryParameters(URL : NSURL!, queryParameters : Dictionary<String, String>) -> NSURL {
let URLString : NSString = NSString(format: "%@?%@", URL.absoluteString!, self.stringFromQueryParameters(queryParameters))
return NSURL(string: URLString as String)!
}
}
let requestController = MyRequestController()
requestController.sendRequest()
希望对您有所帮助
我正在使用 Swift 编写我的第一个基本 IOS 应用程序,它将轮询 Proliphix IP 恒温器并显示温度。我已经使用 Paw 将 HTTP Post 转换为 NSURLSession,但是当我将它加载到 Xcode Playground 时,转换后的代码似乎有 3 个语法错误。
我现在的目标是让它在 Playground 中运行,但最终会在我的 App 代码中使用它。有人可以在您自己的 Xcode Playground 中加载此代码并修复错误并使其正常工作吗? URL 是恒温器的 public IP 地址,如果工作正常,它将轮询恒温器和 return OID4.3.2.3 的值和 = 类似 772&(当前为 77.2度)。
class MyRequestController {
func sendRequest() {
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
/* Create session, and optionally set a NSURLSessionDelegate. */
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
/* Create the Request:
My API (POST http://my-thermostat.dyndns.org:8083/get)
*/
var URL = NSURL(string: "http://my-thermostat.dyndns.org:8083/get")
let request = NSMutableURLRequest(URL: URL!)
request.HTTPMethod = "POST"
// Headers
request.addValue("Basic dXNlcjpwYXNzd29yZA==", forHTTPHeaderField: "Authorization")
// Form URL-Encoded Body
let bodyParameters = [
"OID4.3.2.3": "",
]
let bodyString = self.stringFromQueryParameters(bodyParameters)
request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
}
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
string will be @"day=Tuesday&month=January".
@param queryParameters The input dictionary.
@return The created parameters string.
*/
func stringFromQueryParameters(queryParameters : Dictionary<String, String>) -> String {
var parts: [String] = []
for (name, value) in queryParameters {
var part = NSString(format: "%@=%@",
name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!,
value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
parts.append(part)
}
return "&".join(parts)
}
/**
Creates a new URL by adding the given query parameters.
@param URL The input URL.
@param queryParameters The query parameter dictionary to add.
@return A new NSURL.
*/
func NSURLByAppendingQueryParameters(URL : NSURL!, queryParameters : Dictionary<String, String>) -> NSURL {
let URLString : NSString = NSString(format: "%@?%@", URL.absoluteString!, self.stringFromQueryParameters(queryParameters))
return NSURL(string: URLString)!
}
}
我想我需要在 Playground 中使用上面这段代码才能正常工作吗?
import Foundation
import XCPlayground
最后,我用来转换的 HTTP Post 来自下面,Paw 将其转换为上面的 NSURLSession。
POST /get HTTP/1.1
Authorization: Basic dXNlcjpwYXNzd29yZA==
Content-Type: application/x-www-form-urlencoded
Host: my-thermostat.dyndns.org:8083
Connection: close
User-Agent: Paw/2.2.2 (Macintosh; OS X/10.10.4) GCDHTTPRequest
Content-Length: 11
OID4.3.2.3=
感谢您的帮助!
如果我使用您的代码创建游乐场,我会遇到三个错误。
函数 sendRequest()
中的一个,您必须更改此行:
let statusCode = (response as NSHTTPURLResponse).statusCode
到
let statusCode = (response as! NSHTTPURLResponse).statusCode
(as!
而不是 as
)
函数 stringFromQueryParameters
中的一个,您必须在其中更改以下行
parts.append(part)
至
parts.append(part as String)
(添加 as String
)
还有函数 NSURLByAppendingQueryParameters
中的一个,您必须在其中更改:
return NSURL(string: URLString)!
对此:
return NSURL(string: URLString as String)!
(添加 as String
)
然后编译器似乎很满意......至少在我的机器上 :-)
是的,您需要导入 Foundation 和 XCPlayground,正如您已经知道的那样。
此外,如果您需要进行异步调用...就像这里的情况一样,您需要在代码顶部使用此方法:
XCPSetExecutionShouldContinueIndefinitely()
(您可以阅读更多相关信息 here)
最后,要实际查看您的代码 运行,您可以将其添加到代码底部,在 class 定义之后:
let requestController = MyRequestController()
requestController.sendRequest()
这里是完整的代码
import Foundation
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
class MyRequestController {
func sendRequest() {
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
/* Create session, and optionally set a NSURLSessionDelegate. */
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
/* Create the Request:
My API (POST http://my-thermostat.dyndns.org:8083/get)
*/
var URL = NSURL(string: "http://my-thermostat.dyndns.org:8083/get")
let request = NSMutableURLRequest(URL: URL!)
request.HTTPMethod = "POST"
// Headers
request.addValue("Basic dXNlcjpwYXNzd29yZA==", forHTTPHeaderField: "Authorization")
// Form URL-Encoded Body
let bodyParameters = [
"OID4.3.2.3": "",
]
let bodyString = self.stringFromQueryParameters(bodyParameters)
request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
/* Start a new Task */
let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as! NSHTTPURLResponse).statusCode
println("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
println("URL Session Task Failed: %@", error.localizedDescription);
}
})
task.resume()
}
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
string will be @"day=Tuesday&month=January".
@param queryParameters The input dictionary.
@return The created parameters string.
*/
func stringFromQueryParameters(queryParameters : Dictionary<String, String>) -> String {
var parts: [String] = []
for (name, value) in queryParameters {
var part = NSString(format: "%@=%@",
name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!,
value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
parts.append(part as String)
}
return "&".join(parts)
}
/**
Creates a new URL by adding the given query parameters.
@param URL The input URL.
@param queryParameters The query parameter dictionary to add.
@return A new NSURL.
*/
func NSURLByAppendingQueryParameters(URL : NSURL!, queryParameters : Dictionary<String, String>) -> NSURL {
let URLString : NSString = NSString(format: "%@?%@", URL.absoluteString!, self.stringFromQueryParameters(queryParameters))
return NSURL(string: URLString as String)!
}
}
let requestController = MyRequestController()
requestController.sendRequest()
希望对您有所帮助