简体   繁体   中英

Corrupted data when convert String to NSData in swift

I have a request that take string in request body the string format as following

{"DeviceId":"B7A71027-78B1-4E25-9AC3-350EEB981C58", "TokenId":"B7A71027-78B1-4E25-9AC3-350EEB981C58", "OsType":"ios", "Email":"a.a@a.com", "UserName":"Amira", "Password":"1111", "ProfileImage":""}

but swift request body only accept NSData type so I searched and found the following three lines that convert String to NSData

        let data = parameter.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        let convertedStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
        let finalString = convertedStr!.dataUsingEncoding(NSUTF8StringEncoding)

the problem now that the final string that sent to server is not formated and not accepted by server, it is looked like the following

finalString: 
Optional(<7b224465 76696365 4964223a 22423741 37313032 372d3738 42312d34 4532352d 39414333 2d333530 45454239 38314335 38222c20 22546f6b 656e4964 223a2242 37413731 3032372d 37384231 2d344532 352d3941 43332d33 35304545 42393831 43353822 2c20224f 73547970 65223a22 696f7322 2c202245 6d61696c 223a2261 2e614061 2e636f6d 222c2022 55736572 4e616d65 223a2241 6d697261 222c2022 50617373 776f7264 223a2231 31313122 2c202250 726f6669 6c65496d 61676522 3a22227d>)

so now server give me error, how can I solve this problem please ?

我通过添加解决了问题

request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM