2015-09-06 68 views
-2

我想構建2個函數來構造HTTPBody傳遞給NSURLRequestNSURLRequest中的HTTP正文

功能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. 如何將字符串(swift)轉換爲NSData而不使用NSString?

回答

1

這是點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)! 

希望這會有所幫助。

+0

太棒了!正是我想要的......謝謝一噸! – user1046037

+0

在大多數在線示例中,我已經看到NSJSONSerialization在任何地方都可以使用。重要的部分是它應該滿足您的要求並提供您需要的所需輸出。 – Karlos