NSURLRequest 中的 HTTP 正文

HTTP Body in NSURLRequest

我想构建 2 个函数来构造要传递给 NSURLRequest 的 HTTPBody。

函数1:接受NSDictionary,需要转换成NSData

函数2:接受NSString,需要转换成NSData

函数 1 的代码:

//HTTPBodyParameters is of the type NSDictionary which is the input parameter

    let HTTPBody : NSData?

    do {
        HTTPBody = try NSJSONSerialization.dataWithJSONObject(HTTPBodyParameters, options: NSJSONWritingOptions.PrettyPrinted)
    }
    catch let error as NSError {

        print("Error in creating body - \(error)")

        HTTPBody = nil
    }

问题:

  1. 当输入是 NSDictionary 时,我的代码是否适用于所有场景,还是有更好的方法?

  2. 如何在不使用 NSString 的情况下将 String (swift) 转换为 NSData?

这是第 1 点的答案:

   //You can type cast to AnyObject. So it can accept to NSDictionary and NSString
   request.HTTPBody = NSJSONSerialization.dataWithJSONObject(str as AnyObject, options: nil, error: &error)

这是第 2 点的答案:

 var str: String = "teststring"
 var data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding)!

希望这会有所帮助。