Reputation: 105
i calling Rest API in order to call i have some parameters as dictionary format and passing to api at some point i getting crash in conversion son type
here my sample code :
let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
self.profieImage = UIImage(named: "calendar.png")
let imageData = UIImageJPEGRepresentation(self.profieImage, 1)
let params = ["fname":"Martin","lname":"Raj","gender":"Male","dob":"1997-9-14","email":"[email protected]","mobileNumber":"00000","pancard":"vvvv","profileImg":imageData!] as Dictionary!
let urlString = NSString(format:"http://my.api.call");
print("url string is \(urlString)")
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
request.HTTPMethod = "POST"
request.timeoutInterval = 30
request.addValue("mobile", forHTTPHeaderField: "true")
request.addValue("token", forHTTPHeaderField: "")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let dataTask = session.dataTaskWithRequest(request)
{
(let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
// 1: Check HTTP Response for successful GET request
guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode){
case 200:
let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
print("response==\(response)")
default:
break
}
}
my log prints this statement :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'
Upvotes: 0
Views: 1324
Reputation: 285039
The error message is pretty clear:
NSData
in JSON is not supported.
For example you could convert the data to a Base-64 encoded string
let imageDataBase64 = imageData!.base64EncodedStringWithOptions([])
let params = ["fname":"Martin","lname":"Raj","gender":"Male","dob":"1997-9-14","email":"[email protected]","mobileNumber":"00000","pancard":"vvvv","profileImg":imageDataBase64]
On the server side you need to decode the string back to NSData
params
is a non-optional dictionary (the compiler can infer that), the type casting to implicit unwrapped Dictionary
is meaningless and not needed.
Upvotes: 1