I have an error when trying to kill user session when the logout button is pressed. Anybody have an idea where im going wrong? Thanks in advance
Here is the code
#IBAction func logoutButtonTapped(sender: AnyObject) {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize();
PFUser.logOutInBackgroundWithBlock({ (error:NSError!) -> Void in
self.performSegueWithIdentifier("loginView", sender: self);
})
Error: 'Cannot invoke 'logOutInBackgroundWithBlock' with an argument list of type '((NSError) -> Void)'
Remove the type specifier NSError! from the param.
PFUser.logOutInBackgroundWithBlock({(error) -> Void in
self.performSegueWithIdentifier("loginView", sender: self);
})
Related
Using Xcode 13, typing any substring of print suggests printContent() first in the Xcode code completion list above the common Swift print() function(s).
printContent(_ sender: Any?)
Tells your app to print available content.
"Jump to Definition" displays the following declaration, new for iOS 15 in 2021:
public protocol UIResponderStandardEditActions : NSObjectProtocol {
// ...
#available(iOS 15.0, *)
optional func printContent(_ sender: Any?)
}
What is the printContent() function and how is it used?
Is it in any way a new better replacement for print(), justifying its prominent code completion location in Xcode?
If not, how can I go back to pre-Xcode 13 behavior and suggest the extremely common print() function first in the list?
If your app includes the UIApplicationSupportsPrintCommand key in its Info.plist file, people can print from your app using the keyboard shortcut Command-P, which calls printContent(_:). You can also set printContent(_:) as the action on other print-related controls such as a print button on a toolbar.
override func printContent(_ sender: Any?) {
let info = UIPrintInfo.printInfo()
info.outputType = .photo
info.orientation = .portrait
info.jobName = modelItem.title
let printInteractionController = UIPrintInteractionController()
printInteractionController.printInfo = info
printInteractionController.printingItem = modelItem.image
let completionHandler: UIPrintInteractionController.CompletionHandler = {
(controller: UIPrintInteractionController, completed: Bool, error: Error?) in
if let error = error {
Logger().error("Print failed due to an error: \(error.localizedDescription)")
}
}
if traitCollection.userInterfaceIdiom == .pad {
if let printButton = navigationItem.rightBarButtonItem {
printInteractionController.present(from: printButton, animated: true, completionHandler: completionHandler)
}
} else {
printInteractionController.present(animated: true, completionHandler: completionHandler)
}
}
Apple developer link
I'm creating a macOS SwiftUI app that opens a WKWebView to a specific URL.
Now I'm attempting to make a MenuItem mapped to a function that takes a screenshot of the WKWebView window, and saves it to ~/Pictures with a timestamp.
I tried to look for this via tutorials but only found iOS WKSnapShot type stuff.
While the "MenuItem" -> bind to -> First Responder -> #IBAction is something I'm kind of familiar with now, I'm not entirely sure how to call the WKWebView snapshotting and how to define it's timestamped name.
#IBAction func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?,
completionHandler: #escaping (NSImage?, Error?) -> Void)
{
}
This started shooting errors at me: #IBAction methods must have 1 argument
You just need to call the snapshot function on the webView. To get the webView snapshot function to be available, you need to make it available in the AppDelegate.swift
Then you can save it by using saveImage - which is linked in the handy function at this answer.
public let webView: WKWebView = WKWebView()
#IBAction func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration,
completionHandler: #escaping (NSImage *snapshotImage) -> Void)
{
self.webView.takeSnapshot(with: snapshotConfiguration) { image, error in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
name = (formatter.string(from: Date()) as NSString) as String
if let image = image {
saveImage(name, image)
}
}
}
Using the latest XCode, I'm getting this error:
'logInWithReadPermissions(_:handler:)' is deprecated:
use logInWithReadPermissions:fromViewController:handler: instead'
How would I alternatively re-format my code? here is the whole function that it is in:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"]) {
(facebookResult: FBSDKLoginManagerLoginResult!,facebookError: NSError!) in
print("Facebook login failed. Error \(facebookError)")
}
}
Xcode 8.2 beta (8C30a) :
fbLoginManager.logIn(withReadPermissions:["email"], from: self, handler: {
(result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult? = result
if(fbloginresult?.isCancelled)! {
//Show Cancel alert
} else if(fbloginresult?.grantedPermissions.contains("email"))! {
//self.returnUserData()
//fbLoginManager.logOut()
}
}
})
Figured it out guys! If anyone is lurking on this post, here is the new code:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { (facebookResult: FBSDKLoginManagerLoginResult!, facebookError: NSError!) -> Void in
print("Facebook login failed. Error \(facebookError)")
}
}
If your fbBtnPressed function is in a view controlle class, just pass self to the fromViewController parameter.
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { ... }
A note though, it's encouraged in Swift and Obj-C that your function names prioritize readability over being compact. For example, I would name your button handler facebookLoginButtonPressed. It's longer but much more readable.
The following code worked properly prior to upgrading to Xcode 7.3;
func myMethod() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CreateButtonObject.notifyButtonAction(_:)))
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(CreateButtonObject.notifyButtonAction(_:)))
tapGesture.numberOfTapsRequired = 1
}
#IBAction #objc func notifyButtonAction (sender: AnyObject) {
let userInfo:Dictionary<String,AnyObject!>
print("Sender from tap or longpress: \(sender)")
**let button = sender.view as! UIButton**
let soundName = button.currentTitle!
userInfo = ["sender" : sender]
NSNotificationCenter.defaultCenter().postNotificationName(sleepEZButtonActionNotificationKey, object: nil, userInfo: userInfo)
DDLogDebug("CreateButtonObject.notifyButtonAction: Notificaiton! ButtonViewController")
DDLogDebug("CreateButtonObject.notifyButtonAction: Posted Notification sleepEZButtonActionNotificationKey to initiate buttonAction")
DDLogDebug("CreateButtonObject.notifyButtonAction: Button Name: \(soundName)")
DDLogDebug("")
}
But now when I do this in Xcode 7.3 I get the following error on the line with sender.view ;
Ambiguous use of 'view'
followed by a compiler error.
Anyone know what's going on here and how to fix. Can't figure this out. Basically I need to get the UIButton attributes out of the UITapGesureRecognizer object that is created and then activated on a button press. Stuck.
Thanks in advance...
In the declaration func notifyButtonAction (sender: AnyObject), you have typed sender as AnyObject. But an AnyObject doesn't have a view. So in your line sender.view as! UIButton, the phrase sender.view is illegal.
Type sender as a UIGestureRecognizer if that's what it is: func notifyButtonAction (sender: UIGestureRecognizer). A gesture recognizer does have a view, so all will be well.
I'm trying to make a messaging app in Parse, but I get this error when trying to upload a PFObject.
The error says:
2014-11-22 14:43:21.154 Parse demo[688:27950] Warning: A long-running operation is being executed on the main thread.
Break on warnBlockingOperationOnMainThread() to debug.
and my code is for the sender-button is:
#IBAction func sendButton(sender: AnyObject) {
var message = PFObject(className:"message")
message["message"] = send.text
message.save()
where send.text is just a text-box.
Any recommendations or ways to proceed would be highly appreciated.
Try this instead. then you save in a background blok
#IBAction func sendButton(sender: AnyObject) {
var message = PFObject(className:"message")
message["message"] = send.text
message.saveInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if (error != nil) {
println("Save : \(error)")
}
else{
println("Success! with save")
}
}
}
This is not exactly an error, but more a hint, that it'll block the app because you are making a synchronous save call. Use one of the saveInBackground* methods instead and the save will take place asynchronously on a background job.