swift代码出错:
Login.swift:93:87: Cannot convert value of type ‘String’ to type ‘NSData’ in coercion
let decodedJsonDict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(respJsonStr as NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let respJsonData:NSData = respJsonStr.dataUsingEncoding(NSStringEncoding)
let respJsonData:NSData = respJsonStr.dataUsingEncoding(NSStringEncoding, allowLossyConversion: Bool)
的区别。
letrespJsonData:NSData= respJsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:false)! print(“respJsonData=\(respJsonData)”) |
respJsonData=<7b226163 74697665 223a2074 7275652c 22636f6e 74616374 73223a20 5b5d2c22 646f635f 74797065 223a2022 75736572 222c2265 6d61696c 223a2022 63726966 616e4064 61727975 6e2e636f 6d222c22 6e616d65 223a2022 5c753637 34655c75 38333032 222c2270 61737377 6f726422 3a202231 31313131 31222c22 70686f6e 65223a20 22313530 35313436 34363534 222c2270 696e6e65 64223a20 5b5d7d> |
Returns an
NSData
object containing a representation of the receiver encoded using a given encoding.Declaration
OBJECTIVE-C
- (NSData *)dataUsingEncoding:(NSStringEncoding)
encoding
allowLossyConversion:(BOOL)
flag
Parameters
encoding
A string encoding.
flag
If
YES
, then allows characters to be removed or altered in conversion.Return Value
An
NSData
object containing a representation of the receiver encoded usingencoding
. Returnsnil
ifflag
isNO
and the receiver can’t be converted without losing some information (such as accents or case).Discussion
If
flag
isYES
and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character fromNSUnicodeStringEncoding
toNSASCIIStringEncoding
, the character ‘Á’ becomes ‘A’, losing the accent.This method creates an external representation (with a byte order marker, if necessary, to indicate endianness) to ensure that the resultingNSData
object can be written out to a file safely. The result of this method, when lossless conversion is made, is the default “plain text” format for encoding and is the recommended way to save or transmit a string object.
转载请注明:在路上 » [已解决]swift中string转换为NSData失败:Cannot convert value of type String to type NSData in coercion