gpt4 book ai didi

ios - 在 Swift 中的 WebService 中传递参数

转载 作者:可可西里 更新时间:2023-10-31 23:57:19 27 4
gpt4 key购买 nike

我正在学习 Swift,但我不知道如何使用 Swift 将参数发送到服务器。在 Objective-C 中,我们可以通过使用 "%@" 作为占位符来做到这一点。但是在 Swift 的情况下应该做什么,假设我有一个需要电子邮件和密码的登录网络服务。

现在我想知道的是如何将logintextfieldpasswordtextfield 文本发送到服务器,例如,

var bodyData = "email=logintextfield.text&password=passwordtextfield.text"

最佳答案

当创建包含用户输入的 HTTP 请求时,通常应该对它进行百分号转义,以防用户输入中有任何保留字符,因此:

let login    = logintextfield.text?.addingPercentEncodingForURLQueryValue() ?? ""
let password = passwordtextfield.text?.addingPercentEncodingForURLQueryValue() ?? ""
let bodyData = "email=\(login)&password=\(password)"

请注意,您确实需要检查 loginpassword 是否为 nil。无论如何,百分比转义是按如下方式完成的:

extension String {

/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.

func addingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")

return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}

}

有关此扩展的另一个版本,请参阅 this answer


如果您想观看上述内容的使用演示,请想象以下请求:

let keyData = "AIzaSyCRLa4LQZWNQBcjCYcIVYA45i9i8zfClqc"
let sensorInformation = false
let types = "building"
let radius = 1000000
let locationCoordinate = CLLocationCoordinate2D(latitude:40.748716, longitude: -73.985643)
let name = "Empire State Building, New York, NY"
let floors = 102
let now = Date()

let params:[String: Any] = [
"key" : keyData,
"sensor" : sensorInformation,
"typesData" : types,
"radius" : radius,
"location" : locationCoordinate,
"name" : name,
"floors" : floors,
"when" : now,
"pi" : M_PI]

let url = URL(string: "http://some.web.site.com/inquiry")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = params.dataFromHttpParameters()

let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard data != nil && error == nil else {
print("error submitting request: \(error)")
return
}

if let httpResponse = response as? HTTPURLResponse where httpResponse.statusCode != 200 {
print("response was not 200: \(response)")
return
}

// handle the data of the successful response here
}
task.resume()

我包含了很多您的示例中未包含的参数,但只是为了说明例程对各种参数类型数组的处理方式。

顺便说一下,上面使用了我的 datafromHttpParameters 函数:

extension Dictionary {

/// This creates a String representation of the supplied value.
///
/// This converts NSDate objects to a RFC3339 formatted string, booleans to "true" or "false",
/// and otherwise returns the default string representation.
///
/// - parameter value: The value to be converted to a string
///
/// - returns: String representation

private func httpStringRepresentation(_ value: Any) -> String {
switch value {
case let date as Date:
return date.rfc3339String()
case let coordinate as CLLocationCoordinate2D:
return "\(coordinate.latitude),\(coordinate.longitude)"
case let boolean as Bool:
return boolean ? "true" : "false"
default:
return "\(value)"
}
}

/// Build `Data` representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped

func dataFromHttpParameters() -> Data {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).addingPercentEncodingForURLQueryValue()!
let percentEscapedValue = httpStringRepresentation(value).addingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}

return parameterArray.joined(separator: "&").data(using: .utf8)!
}

}

这里,因为我处理的是一个参数字符串数组,所以我使用join函数将它们连接起来,用&分隔,但思路是一样的。

随意自定义该函数以处理您可能传递给它的任何数据类型(例如,我通常没有 CLLocationCoordinate2D ,但您的示例包含一个,所以我想展示它可能看起来像什么)。但关键是,如果您提供任何包含用户输入的字段,请确保对其进行百分比转义。

仅供引用,这是我在上面使用的 rfc3339String 函数。 (显然,如果您不需要传输日期,则不需要这个,但为了更通用的解决方案的完整性,我将其包括在内。)

extension Date {

/// Get RFC 3339/ISO 8601 string representation of the date.
///
/// For more information, see:
///
/// https://developer.apple.com/library/ios/qa/qa1480/_index.html
///
/// - returns: Return RFC 3339 representation of date string

func rfc3339String() -> String {
let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")

return formatter.string(from: self)
}
}

要查看 Swift 2 版本,请参阅此答案的 previous rendition

关于ios - 在 Swift 中的 WebService 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154546/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com