I have written an iOS app that uses Parse.com. When I need to change the information about a user I use refreshInBackgroundWithBlock. I am now writing the app for Mac OS X but I do not seem to be able to use refreshInBackgroundWithBlock. Any Suggestions?
Here is the code below.
//Refresh the User Info
currentUser.refreshInBackgroundWithBlock { (object, error) -> Void in
//Fetch the User Info
currentUser.fetchIfNeededInBackgroundWithBlock { (result, error) -> Void in
//Check if the comments read is nil
if object.objectForKey("commentsRead") === nil {
println("Comments Read is empty")
} else {
var currentRead:[Int] = []
//If not empty assign the array to the value
currentRead = object.objectForKey("commentsRead") as Array
currentRead.append(0)
var user = PFUser.currentUser()
user.setObject(currentRead, forKey: "commentsRead")
user.saveInBackgroundWithBlock { (result, error) -> Void in
println("Completed!")
}
}
According to the parse doc, refreshInBackgroundWithBlock is deprecated and replaced by fetchInBackgroundWithBlock (See this)
So you don't need to call refreshInBackgroundWithBlock.
Related
I am new to Parse. I am trying to update a object already saved on the parse backend. I use the getObjectInBackgroundWithID and supply the object ID. When I try and update with new data the app tells me it successfully save a new record and when i look on the backend, I now have two records with different object ID's. Below is my code in the update button. In my app it passes in the object ID, but I have tried hard coding the object ID with the same result.
#IBAction func updateAccountPressed(sender: AnyObject) {
let query = PFQuery(className:"Accounts")
query.getObjectInBackgroundWithId("dS7fHCoabI") {
(accountInfo: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let accountInfo = accountInfo {
accountInfo["Type"] = self.pickedAccontType
accountInfo["NumberOrNickname"] = self.accountNumNickname.text
accountInfo["InitialBalance"] = self.initialBalance.text
accountInfo.saveInBackground()
}
}
When you do
...
} else if let accountInfo = accountInfo {
...
You are actually creating a new variable called accountInfo and assigning the object you fetched to it. You are then calling the saveInBackground() method on a new PFObject you just created, thus creating a new record in Parse. Just change your if statement:
if error != nil {
print(error)
} else {
accountInfo["Type"] = self.pickedAccountType
accountInfo["NumberOrNickname"] = self.accountNumNickname.text
accountInfo["InitialBalance"] = self.initialBalance.text
accountInfo.saveInBackground()
}
It turns out I had somehow linked my updated button with both my update and the add func. After removing the link it updates fine with no new objectID.
I want to convert the friend list ids that I am getting from facebook as an array to save in parse. My code is as below but I am getting a "unexpectedly found nil while unwrapping an Optional value" error. What should I do to save the result to parse and retrieve it as array when required?
let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
if let dict = result as? Dictionary<String, AnyObject>{
let profileName:NSArray = dict["name"] as AnyObject? as! NSArray
let facebookID:NSArray = dict["id"] as AnyObject? as! NSArray
print(profileName)
print(facebookID)
}
}
else {
print("Error Getting Friends \(error)");
}
}
When I use the code below in print() I get the result below:
Friends are : {
data = (
{
id = 138495819828848;
name = "Michael";
},
{
id = 1105101471218892;
name = "Johnny";
}
);
The issue is that you are trying to access the name and id elements from the top-level dictionary, where you need to be accessing data.
When you call the FB Graph API for friends it will return an array of dictionaries (one per friend).
Try this:
let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil)
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
if let friendObjects = result["data"] as? [NSDictionary] {
for friendObject in friendObjects {
println(friendObject["id"] as NSString)
println(friendObject["name"] as NSString)
}
}
} else {
print("Error Getting Friends \(error)");
}
}
You should also check out this SO post with more information on the FB Graph API. Here's a brief snippet.
In v2.0 of the Graph API, calling /me/friends returns the person's
friends who also use the app.
In addition, in v2.0, you must request the user_friends permission
from each user. user_friends is no longer included by default in every
login. Each user must grant the user_friends permission in order to
appear in the response to /me/friends. See the Facebook upgrade guide
for more detailed information, or review the summary below.
I'm pretty new in OS X programming and I'm trying to write an application that will capture Force Click event at system-wide context.
Based on various sources I wrote down code listed below:
var lastClickStage = -1
func checkAssistanceSettings () -> Bool {
let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString
let options = [checkOptPrompt: true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
return accessEnabled == 1
}
func processForceClick(incomingEvent: NSEvent!) -> Void {
let clickStage = incomingEvent.stage
if clickStage == lastClickStage {
return
}
if (lastClickStage == 2 && clickStage != 2) {
lastClickStage = clickStage
return
}
if (clickStage == 2 && lastClickStage != 2) {
let applicationClicked = NSWorkspace.sharedWorkspace().frontmostApplication?.bundleIdentifier
if (applicationClicked != nil) {
NSLog("ForceClicked in \(applicationClicked!)!")
}
lastClickStage = clickStage
}
}
func processForceClickLocally(incomingEvent: NSEvent!) -> NSEvent {
processForceClick(incomingEvent)
return incomingEvent
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSLog("\(checkAssistanceSettings())")
NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMaskFromType(NSEventType.EventTypePressure), handler: processForceClickLocally)
NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMaskFromType(NSEventType.EventTypePressure), handler: processForceClick)
}
When I run my application local event listener seems to work like a charm, but global event listener never calls his handler, even if XCode or a specific built application gets grant to accessibility in System Settings (AXIsProcessTrustedWithOptions(options) evaluates as "true").
Can anyone point out what's wrong with it?
EDIT: Even strange thing discovered by me: seems like global listener not working with this NSEventMask. Got no problem with NSEventMask.LeftMouseDownMask for example.
So now seems like question is transformed to "What wrong with NSEventMask.EventMaskPressure in global listeners?".
I couldn't find any info about getting user's location info in swift and xcode 6
I tried
var fbcity = user.objectForKey("location")
var fbcountry = user.objectForKey("country")
But didn't work.
Any idea how to achieve this ?
Perhaps you could supply us with a little more information, e.g. which Facebook SDK you are using and what parameters FBSDKGraphRequest has to return user. Note that there is no specific information about country, the location field in the user node when your send a graph request for the user profile. It will return the subfields: id and name, where name is
With the latest Facebook iOS SDK 4.0 you can do something like:
override func viewDidLoad() {
super.viewDidLoad()
self.loginView.delegate = self
if FBSDKAccessToken.currentAccessToken() != nil {
fetchUserData()
} else {
loginView.readPermissions = ["public_profile", "email", "user_friends"]
}
}
func fetchUserData() {
let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if error != nil {
// Process error
println("Error: \(error)")
} else {
let location: NSDictionary! = result.valueForKey("location") as NSDictionary
let city: NSString = location.valueForKey("name") as NSString
}
})
}
More detailed info can be found on Facebook Graph API User page.
I use Alamofire for networking in my iOS application. I need to run this app in iOS 7+. I want to indicate network activity in status bar, so I created this struct:
struct ActivityManager {
static var activitiesCount = 0
static func addActivity() {
if activitiesCount == 0 {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
activitiesCount++
}
static func removeActivity() {
if activitiesCount > 0 {
activitiesCount--
if activitiesCount == 0 {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
}
}
But I don't know, where to call in code addActivity() and removeActivity() methods. I don't want to write them with every request. I want to, that they will be called automatically with every request.
I tried also use pure NSURLSession and NSURLSessionTask and extend them:
extension NSURLSessionTask {
func resumeWithActivity() {
ActivityManager.addAction()
self.resume()
}
}
public extension NSURLSession {
func OwnDataTaskWithRequest(request: NSURLRequest!, ownCompletionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask! {
return self.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
ActivityManager.removeAction()
ownCompletionHandler!(data, response, error)
})
}
}
Then I used them like this:
var session: NSURLSession = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
session.OwnDataTaskWithRequest(request) { (data, response, error) -> Void in
// some logic here
}.resumeWithActivity()
But this approach doesn't work. In iOS 7 is NSURLSession extension not visible. I created a bug report for this (with sample project).
Can you please give me some advise, how to reach my goal? With or without Alamofire?
If you don't want to call your functions manually for every request and that you want to use Alamofire, I suggest you to improve it to add the network activity indicator feature.
Have a look at the source of Alamofire
You need to register 2 notification observers in your ActivityManager and then trigger the notifications at the relevant places either in Alamofire.Manager or in Alamofire.Request.
Also have a look at the source of AFNetworkActivityIndicatorManager which implement the feature you want in AFNetworking.