Search code examples
stringswiftutf-8nsdata

HTTP Body in NSURLRequest


I want to build 2 functions to construct the HTTPBody to pass to NSURLRequest.

Function 1: Accepts NSDictionary, which needs to converted into NSData

Function 2: Accepts NSString, which needs to converted into NSData

Code For Function 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
    }

Questions:

  1. Does my code hold good for all scenarios when the input is an NSDictionary or is there a better approach ?

  2. How to convert String (swift) into NSData without using NSString ?


Solution

  • This is the answer for point 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)
    

    This is the answer for point 2:

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

    Hope this will be helpful.