我正在使用swift创建一个ios应用程序,其中一部分通过json(NSData)将数据发送到远程Web API。当我使用xcode 6 beta时它工作正常,但升级到xcode 6.0.1后它返回一个我真的无法理解的错误。
我想知道是否有人可以帮我解决这个问题。
错误是:
GeneralFunctions.swift:37:35: 'NSData?' does not have a member named 'length'
我的功能是:
func sendData(req_url:String, data:String) -> String{
let url = NSURL(string: req_url)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = data
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// set content length
NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
// println("API Response: \(results)")
return results
}
谢谢大家。
答案 0 :(得分:1)
错误是因为requestBodyData没有属性长度,因为它是一个未被取出的可选项。
它应该工作我执行requestBodyData!.length而不是requestBodyData.length(添加!获取实际具有.length选择器的NSData对象)。
阅读选项:https://medium.com/@rrridges/swift-optionals-a10dcfd8aab5