NSURLRequest中的HTTP正文

用户名

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

功能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)

这是第二点的答案:

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

希望这会有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章