How do you set a row of parse data to be equal to label text or button text? If someone could leave me the code to do this.
The label outlet name is BookName.
I have all of the code written in swift.
Thanks,
Jeff
You can do this like so:
Create a function to fetch the object
func getPFObject() {
let query = PFQuery(className: "YourClassName")
//set your key that you're looking for here
query.findObjectsInBackgroundWithBlock { ( objects: [PFObject]?, error) -> Void in
if error == nil {
self.BookName.text = objects[0]["foo"] as! String
}
}
And then in viewDidAppear: or elsewhere
self.getPFObject()
As convention, you probably shouldn't start your variable names (like your outlets) with capital letters, it will throw people on SO off! And it's bad style too.
Related
Im more familiar with ActionScript3 and see many similarities in Swift2, kind of why i am trying out basic coding in Swift2 and Xcode.
Here's my example:
#IBOutlet weak var b1CurrSpeed: NSTextField!
I want to store b1CurrSpeed as a string so i could access the actual textfield component to set its default value when application is loaded.
I'm aiming for Swift2 for osx apps.
Here is a fictional example, not related to any actual code:
var tf:NSTextField = this.getItem("b1CurrSpeed");
tf.stringValue = "Hello world";
Reason to this approach is following...
I would like to store textfield value in NSUserDefaults, the key for defaults would be name of that textfield. So when looping thru the defaults, i would like to get key as string and when ive got that i'd have access to actual component to set its stringvalue property.
Tho, is that good approach in Swift / xCode ?
If you want to create a function for it, do someting like this:
func getStringForKey(key: String) -> String {
guard let result = NSUserDefaults.standardUserDefaults().objectForKey(key) as! String else { return "" }
return result
}
You can set the TextFields value with myTextField.text
Swift's Mirror type can get you close to it but it is limited to NSObject subclasses, can only access stored properties and is read-only.
Yet, there are ways around these limitations if your requirements will allow.
For example, here's an extension that will save and restore defaults values for all UITextfields on a view controller using the name you gave to each IBOutlet.
extension UIViewController
{
func loadDefaults(userDefaults: NSUserDefaults)
{
for prop in Mirror(reflecting:self).children
{
// add variants for each type/property you want to support
if let field = prop.value as? UITextField,
let name = prop.label
{
if let defaultValue = userDefaults.objectForKey(name) as? String
{ field.text = defaultValue }
}
}
}
func saveDefaults(userDefaults: NSUserDefaults)
{
for prop in Mirror(reflecting:self).children
{
if let field = prop.value as? UITextField,
let name = prop.label
{
if let currentValue = field.text
{ userDefaults.setObject(currentValue, forKey: name) }
}
}
}
}
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 :)
(I'm new to programming and totally new to Parse, so simplified explanations are certainly appreciated)
I imagine this is pretty straightforward; I'm just stuck. I have a PFObject saved in Parse.com that contains an array containing strings. I'm trying to set an array in my Swift app with the values in the Parse array.
var query = PFQuery(className:"ParseHat")
query.getObjectInBackgroundWithId("xxxxxxxxxx")
submittedNames = query["theHat"] as [String]
// submittedNames is declared elsewhere in the code. "theHat" is the key where
the array is stored in the PFobject
I get the error 'PFQuery' does not have a member named 'subscript'. I've tried doing a few things I didn't fully understand to the code but have gotten other errors so I'm just posting this as it seems to most closely resemble the method for retrieving objects in the Parse docs.
Try this out...
var query = PFQuery(className: "ParseHat")
query.getObjectInBackgroundWithId("XXXXXXXXX") {
(objects: PFObject?, error: NSError?) -> Void in
if error == nil {
//fetching users
for object in objects{ //looping through returned data
self.resultsArray.append(object.objectForKey("XXXXXXXX") as! String)
//adding the string to var resultsArray = [String]()
}
} else {
println("error :(")
}
}
Environment: Debugging Parse return object within Xcode 6.1
I can see the text within the object structure but can't adequately view its assigned variable.
Here's the code:
func retrieveAllMediaFromParse() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let myData:PFQuery = PFQuery(className: kParseMedia)
myData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if !(error != nil){
// for object in objects {
let myObject = objects[0] as PFObject
let format = myObject.objectForKey("format") as String
let access = myObject.objectForKey("access") as String
let media = myObject.objectForKey("media") as String
let owner = myObject.objectForKey("owner") as String
let text = myObject.objectForKey("text") as String
let thumbNail = myObject.objectForKey("thumbnail") as NSString
}
}
});
}
let text = myObject.objectForKey("text") as String
When I take the 'po' of the command string I get the correct interpretation:
However, when I do the same for the assigned variable (constant), I get the following:
How do I view the variable/constant to display the actual string?
When program is paused in the debugger, you can find the values of PFObject fields by going to the estimatedData line in the debugger.
I have spent all day trying to get useable results from NSURL.getResourceValue for NSURLTagNamesKey in swift. The function should take the path name as a string and return an array of strings for the user tags. I have a version of this that works in Objective C, but have not been able to re-write in Swift.
This is the current version of the code:
func listTags(filePath:String)->[String]{
//convert path string to NSURL
let theURL : NSURL = NSURL.fileURLWithPath(filePath)!
//get tags for NSURL -- should be NSArray of NSStrings hiding in an AnyObject?
var tags : AnyObject?
var anyError: NSError?
tags = theURL.getResourceValue(&tags, forKey:NSURLTagNamesKey, error: &anyError)
//unwrap tags object? This part never works
let tagArray = tags! as [AnyObject]
//insert every item in tag array into results array as a String
var results = [String]()
for object in tagArray{
results.append(object as String)
}
return results
}
The code will compile but breaks when it tries to convert the AnyObject to any other type. I have tried every combination I can think of -- [AnyObject], [String], NSArray, with/without exclamation points and question marks.
Am on verge of giving up on Swift.
You're going to kick yourself...
The method getResourceValue:forKey:error returns a value - a Bool, indicating whether the container you passed in as the first argument has been populated. Unfortunately you're assigning the value of this boolean to tags - your container! - which means that whatever was passed in to this container by Cocoa is immediately over-written. This worked for me...
var tags : AnyObject?
var anyError: NSError?
var success = theURL.getResourceValue(&tags,
forKey:NSURLTagNamesKey,
error: &anyError)
if success {
println("container contents \(tags as [String])") // -> [AutoLayout, Swift]
}
With Swift 2, getResourceValue(:forKey:) returns () throws, i.e., void type which throws errors, so the answer above will no longer work. It needs to be wrapped in a do {try} catch{} construction without the anyError variable:
do {
try theURL.getResourceValue(&tags, forKey: NSURLTagNamesKey)
return tags as! [String]
} catch {
// process the error here
}