Creating NSData from NSString in Swift - xcode

I'm trying to ultimately have an NSMutableURLRequest with a valid HTTPBody, but I can't seem to get my string data (coming from a UITextField) into a usable NSData object.
I've seen this method for going the other way:
NSString(data data: NSData!, encoding encoding: UInt)
But I can't seem to find any documentation for my use case. I'm open to putting the string into some other type if necessary, but none of the initialization options for NSData using Swift seem to be what I'm looking for.

In Swift 3
let data = string.data(using: .utf8)
In Swift 2 (or if you already have a NSString instance)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
In Swift 1 (or if you have a swift String):
let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)
Also note that data is an Optional<NSData> (since the conversion might fail), so you'll need to unwrap it before using it, for instance:
if let d = data {
println(d)
}

Swift 4 & 3
Creating Data object from String object has been changed in Swift 3. Correct version now is:
let data = "any string".data(using: .utf8)

In swift 5
let data = Data(YourString.utf8)

Here very simple method
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

Swift 4
let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)

// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")
var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!

To create not optional data I recommend using it:
let key = "1234567"
let keyData = Data(key.utf8)

Convert String to Data
extension String {
func toData() -> Data {
return Data(self.utf8)
}
}
Convert Data to String
extension Data {
func toString() -> String {
return String(decoding: self, as: UTF8.self)
}
}

Swift 4.2
let data = yourString.data(using: .utf8, allowLossyConversion: true)

Related

SceneKit Swift3 compiler-error

I'm trying to run animated "DAE" model in SceneKit:
let url = Bundle.main.url(forResource: "art.scnassets/Player(walking)", withExtension: "dae")
let sceneSource = SCNSceneSource(url: url!, options: [SCNSceneSource.LoadingOption.animationImportPolicy: SCNSceneSource.AnimationImportPolicy.playRepeatedly] )
let animationIds: NSArray = sceneSource?.identifiersOfEntries(withClass: CAAnimation)
for eachId in animationIds {
let animation: CAAnimation = (sceneSource?.entryWithIdentifier(eachId as! String, withClass: CAAnimation.self))!
animations.add(animation)
}
character?._walkAnimations = animations
But compiler It throws on the line:
let animationIds: NSArray = sceneSource?.identifiersOfEntries(withClass: CAAnimation)
and writes an error:
Cannot convert value of type '[String]?' to specified type 'NSArray'
Please help me to fix that problem.
Thanks in advance.
Why you are converting [String]? to NSArray and then convert each element to String again, no need of it simply use Swift native Array and wrapped the optional value with if let or guard let.
guard let animationIds = sceneSource?.identifiersOfEntries(withClass: CAAnimation) else {
return
}
for eachId in animationIds {
if let animation = sceneSource?.entryWithIdentifier(eachId, withClass: CAAnimation.self) {
animations.add(animation)
}
}
character?._walkAnimations = animations

Passing Dictionary to Watch

I'm trying to pass data from iPhone -> Watch via Watch Connectivity using background transfer via Application Context method.
iPhone TableViewController
private func configureWCSession() {
session?.delegate = self;
session?.activateSession()
print("Configured WC Session")
}
func getParsePassData () {
let gmtTime = NSDate()
// Query Parse
let query = PFQuery(className: "data")
query.whereKey("dateGame", greaterThanOrEqualTo: gmtTime)
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let objectsFromParse = objects as? [PFObject]{
for MatchupObject in objectsFromParse
{
let matchupDict = ["matchupSaved" : MatchupObject]
do {
try self.session?.updateApplicationContext(matchupDict)
print("getParsePassData iPhone")
} catch {
print("error")
}
}
}
}
}
}
I'm getting error twice printed in the log (I have two matchups in Parse so maybe it knows there's two objects and thats why its throwing two errors too?):
Configured WC Session
error
error
So I haven't even gotten to the point where I can print it in the Watch app to see if the matchups passed correctly.
Watch InterfaceController:
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
let matchupWatch = applicationContext["matchupSaved"] as? String
print("Matchups: %#", matchupWatch)
}
Any ideas? Will post any extra code that you need. Thanks!
EDIT 1:
Per EridB answer, I tried adding encoding into getParsePassData
func getParsePassData () {
let gmtTime = NSDate()
// Query Parse
let query = PFQuery(className: "data")
query.whereKey("dateGame", greaterThanOrEqualTo: gmtTime)
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let objectsFromParse = objects as? [PFObject]{
for MatchupObject in objectsFromParse
{
let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject)
let matchupDict = ["matchupSaved" : data]
do {
try self.session?.updateApplicationContext(matchupDict)
print("getParsePassData iPhone")
} catch {
print("error")
}
}
}
}
}
}
But get this in the log:
-[PFObject encodeWithCoder:]: unrecognized selector sent to instance 0x7fbe80d43f30
*** -[NSKeyedArchiver dealloc]: warning: NSKeyedArchiver deallocated without having had -finishEncoding called on it.
EDIT 2:
Per EridB answer, I also tried just pasting the function into my code:
func sendObjectToWatch(object: NSObject) {
//Archiving
let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject)
//Putting it in the dictionary
let matchupDict = ["matchupSaved" : data]
//Send the matchupDict via WCSession
self.session?.updateApplicationContext(matchupDict)
}
But get this error on the first line of the function:
"Use of unresolved identifer MatchupObject"
I'm sure I must not be understanding how to use EridB's answer correctly.
EDIT 3:
NSCoder methods:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
//super.init(coder: aDecoder)
configureWCSession()
// Configure the PFQueryTableView
self.parseClassName = "data"
self.textKey = "matchup"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
Error
You are getting that error, because you are putting a NSObject (MatchupObject) which does not conform to NSCoding inside the dictionary that you are going to pass.
From Apple Docs
For most types of transfers, you provide an NSDictionary object with
the data you want to send. The keys and values of your dictionary must
all be property list types, because the data must be serialized and
sent wirelessly. (If you need to include types that are not property
list types, package them in an NSData object or write them to a file
before sending them.) In addition, the dictionaries you send should be
compact and contain only the data you really need. Keeping your
dictionaries small ensures that they are transmitted quickly and do
not consume too much power on both devices.
Details
You need to archive your NSObject's to NSData and then put it in the NSDictionary. If you archive a NSObject which does not conform to NSCoding, the NSData will be nil.
This example greatly shows how to conform a NSObject to NSCoding, and if you implement these things then you just follow the code below:
//Send the dictionary to the watch
func sendObjectToWatch(object: NSObject) {
//Archiving
let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject)
//Putting it in the dictionary
let matchupDict = ["matchupSaved" : data]
//Send the matchupDict via WCSession
self.session?.updateApplicationContext(matchupDict)
}
//When receiving object from the other side unarchive it and get the object back
func objectFromData(dictionary: NSDictionary) -> MatchupObject {
//Load the archived object from received dictionary
let data = dictionary["matchupSaved"]
//Deserialize data to MatchupObject
let matchUpObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MatchupObject
return matchUpObject
}
Since you are using Parse, modifying an object maybe cannot be done (I haven't used Parse in a while, so IDK for sure), but from their forum I found this question: https://parse.com/questions/is-there-a-way-to-serialize-a-parse-object-to-a-plain-string-or-a-json-string which can help you solve this problem easier than it looks above :)

How to write an array to NSUserDefaults in Swift

I'm trying to write the contents of an array to NSUserDefaults, but the app hangs when I call setObject:withKey with the array as the object. Here's the relevant code:
class Contact: NSObject {
var name:String = ""
var number:String = ""
}
var contacts:[Contact]?
contacts = [Contact]()
let contact = Contact()
contact.name = "Joe"
contact.number = "123-4567"
contacts.append(contact)
let defaults = NSUserDefaults.standardUserDefaults()
// Never returns from this when I step over it in the debugger
defaults.setObject(contacts, forKey: "contacts")
defaults.synchronize()
What am I doing wrong?
Not sure exactly how it works on OS X, but if it's anything like it is on iOS, you can't store custom classes in NSUserDefaults, only Strings, Ints, Data, etc... so one work around is to convert your array to NSData and then store it as data and when you retrieve it cast it to be [Contact]. It may look something like this:
let data = NSKeyedArchiver.archivedDataWithRootObject(contacts)
let defaults = NSUserDefaults.standardUserDefaults()
// Storing the data
defaults.setObject(data, forKey: "contacts")
// Retrieving the data
if let data = defaults.objectForKey("contacts") as? NSData {
if let contacts = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Contact] {
// Now you have your contacts
}
}
However, if you are storing large amounts of data, you should probably consider other forms of data management.

Swift optional chaining with NSDictionary

Please help to remake this
if let field = parent_obj?.getFieldForCode(code) {
if let stored_value = field["value"] as? String {
into optional chaining syntax in single line. I tried to do it like this:
let stored_value = parent_obj?.getFieldForCode(code)?["value"] as? String
and got an error:
Type 'String' does not conform to protocol 'NSCopying'
This is my function header:
func getFieldForCode(code: String) -> NSDictionary?
Is it possible? I ask it because any time I work with NSArrays and NSDictionaries my code looks terrible:
if let code = self.row_info["code"] as? String {
if let value_field = self.row_info["value_field"] as? String {
if let field = parent_obj?.getFieldForCode(code) {
if let stored_value = field["value"] as? String {
if let fields = self.fields_set{
if let current_value = fields[indexPath.row][value_field] as? String {
Any advices?
You can't cast it directly to a String because you're pulling it from an NSDictionary and, like the error says, String doesn't conform to NSCopying. However, String is bridged to NSString, and NSString does conform to NSCopying. So, with a little bit of casting/bridging trickery, you can make it work like this:
let stored_value: String? = parent_obj?.getFieldForCode(code)?["value"] as? NSString
Note: If you're using this in an optional binding (which it looks like you want to), don't forget to drop the ? from stored_value's type declaration:
if let stored_value: String = parent_obj?.getFieldForCode(code)?["value"] as? NSString {
/* ... */
}

Creating a CTTypesetter in Swift

I have an obj-c class that creates a CFAttributedStringRef:
- (CFAttributedStringRef)createAttributedStringWithByteRange:(NSRange)byteRange
{
UInt8 bytes[byteRange.length];
[self.data getBytes:&bytes range:byteRange];
CFStringRef string = CFStringCreateWithBytes(NULL, bytes, byteRange.length, kCFStringEncodingUTF8, (byteRange.location == 0));
return CFAttributedStringCreate(NULL, string, (__bridge CFDictionaryRef)(self.textAttributes));
}
And I'm trying to call that function from a swift object, which should create a CTTypesetter:
let stringToDraw = self.storage.createAttributedStringWithByteRange(self.line.range)
let typesetter = CTTypesetterCreateWithAttributedString(stringToDraw)
Which gives me this build error:
error: cannot convert the expression's type 'CTTypesetter!' to type '$T3'
let typesetter = CTTypesetterCreateWithAttributedString(stringToDraw)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Anybody have any idea what I'm doing wrong?
I found the problem, the build error was misleading.
The actual problem was the previous line — my obj-c method returning CFAttributedStringRef bridges to Unmanaged<CFAttributedString> and needs to be brought into Swift as a managed object before it can be used, via the takeRetainedValue() method:
let stringToDraw = self.storage.createAttributedStringWithByteRange(self.line.range).takeRetainedValue()
let typesetter = CTTypesetterCreateWithAttributedString(stringToDraw)
You need to refer to the object type as a CTTypesetterRef, not CTTypesetter.
import Foundation
import CoreText
extension NSString
{
func test() -> CTTypesetterRef
{
let attributedString : CFAttributedStringRef?
let typesetter : CTTypeSetterRef = CTTypesetterCreateWithAttributedString(attributedString)
return typesetter
}
}

Resources