我正在用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
}


谢谢你们。

最佳答案

该错误是因为requestBodyData没有属性长度,因为它是尚未被取出的可选属性。

如果您执行requestBodyData!.length而不是requestBodyData.length(它添加!会为您提供具有.length选择器的实际NSData对象),它应该可以正常工作。

阅读可选内容:https://medium.com/@rrridges/swift-optionals-a10dcfd8aab5

07-24 20:26