I have UTF-8 encoded NSData
from windows server and I want to convert it to NSString
for iPhone. Since data contains characters (like a degree symbol) which have different values on both platforms, how do I convert data to string?
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
- Attempt to present UIAlertController on View Contr
You could call this method
I humbly submit a category to make this less annoying:
and
(Note that if you're not using ARC you'll need an
autorelease
there.)Now instead of the appallingly verbose:
You can do:
Sometimes, the methods in the other answers don't work. In my case, I'm generating a signature with my RSA private key and the result is NSData. I found that this seems to work:
Objective-C
Swift
Just to summarize, here's a complete answer, that worked for me.
My problem was that when I used
The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with
Null
or even worse: garbaged at the end of the string.After some digging I switched to
And got the expected result every time.
If the data is not null-terminated, you should use
-initWithData:encoding:
If the data is null-terminated, you should instead use
-stringWithUTF8String:
to avoid the extra\0
at the end.(Note that if the input is not properly UTF-8-encoded, you will get
nil
.)Swift variant:
If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.
The Swift version from String to Data and back to String:
Xcode 9 • Swift 4
Playground