I am working on sharing a content on Facebook for an iOS app using Swift.
I have written a singleton class called FBManager and a function as below.
func shareContent(content:String, contentURL:String?, contentTitle:String? , fromController controller:UIViewController {
let shareDialog = FBSDKShareDialog()
let shareLinkContent = FBSDKShareLinkContent()
shareLinkContent.contentDescription = content
if let url = contentURL
{
shareLinkContent.contentURL = NSURL(string: url)
}
if let title = contentTitle
{
shareLinkContent.contentTitle = title
}
shareDialog.delegate = self
shareDialog.fromViewController = controller
shareDialog.shareContent = shareLinkContent
shareDialog.show()
}
But this does not even show a share dialog both on iOS 8 and iOS 9.
Instead the following delegate method gets called
func sharer(sharer: FBSDKSharing!, didFailWithError error: NSError!) {
}
with the error - "The operation couldn’t be completed. (com.facebook.sdk.share error 2.)"
Can someone please help ?
Facebook SDK's error codes are somewhat ambiguous because they cover rather large domains of errors. The code you provided does not really show the content of the variables and so I cannot pinpoint the problem. However, com.facebook.sdk.share error 2 is an Invalid Argument error, which usually arises from an invalid format of one or more members of FBSDKShareLinkContent.
Generally, you can use the FBSDKErrorCode enum to switch over the (error as NSError).code and find which domain it belongs to. (In this case, it'll point to Invalid Argument)
You can also print(error) directly in the didFailWithError delegate method, which will output a very descriptive log of the error and what caused it specifically.
Check your contentURL, make sure it starts with http:// or https:// or any other valid protocol. Same for the imageURL if you're using or planning to use one. This most likely caused your error!
The SDK's error codes reference may be helpful too.
Related
So I'm trying to create a user on my database backend, everything is working on the app bar this segment on xcode, written in swift.
The backend can accept new users via this method but for some reason swift won't have it.
When I click register I get the error shown in the photo, code used
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName.text!,"email": userMail.text!,"password":userPassword.text!,"profile_photo": self.imageName])
and the output is
<spotimusic.RadioStyleCollectionViewController: 0x7fe313d8fd00> whose view is not in the window hierarchy!
SDSD - Optional("nathan#trojan-audio.com")
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Another error which shows in a segment is
Thanks for any help or suggestions
It seems that userName.text or userPassword.text doesn't have a value. This error can occur due to an unlinked outlet.
If your outlets are linked properly try this:
guard let userName = userName.text, let userMail = userMail.text, let userPassword = userPassword.text else {
return
}
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName,"email": userMai,"password":userPassword,"profile_photo": self.imageName])
You will be able to catch the empty values without crashes.
Let me know if it fixes your problem
Thanks for all of the help guys, Marco's answer was the one that I used that fixed all the errors.
guard let userName = userName.text, let userMail = userMail.text, let userPassword = userPassword.text else {
return
}
Alamofire.request(.POST, urlRequest, parameters: ["X-API-KEY": API_GENERAL_KEY,"username":userName,"email": userMai,"password":userPassword,"profile_photo": self.imageName])
I have an App which uses the FBSDKMessageDialog from the actual Facebook iOS SDK to communicate with friends.
Actually i have the problem that the Facebook Messenger is directly switching back to my App (80% of all tries - sometimes it works). Without any user interaction. Normally it should switch back to my App after sending the Message.
That's what i am doing:
if(UIApplication.sharedApplication().canOpenURL(NSURL(string: "fb-messenger://")!)) {
let content = FBSDKShareLinkContent()
content.contentDescription = description;
content.contentTitle = title
content.contentURL = NSURL(string: url)
content.imageURL = NSURL(string: self.appIconUrl)
FBSDKMessageDialog.showWithContent(content, delegate: self)
}
**Update
Found a new hint with func sharer(sharer: FBSDKSharing!, didFailWithError error: NSError!)
Error Domain=com.facebook.Facebook.platform Code=103 "(null)" UserInfo={error_message=Error parsing link, error_code=103, app_id=870185466371832}
I will check that.
**Update #2
After unwrapping the URL it still doesn't work. The URL looks good but the same error. If i define google.com as URL it seems to work all the time...very strange.
I tried to share a Facebook Open Graph Action via official iOS SDK (last version) but for a few days now, this action returns an error and it has now stopped working.
The app passed the Facebook approval, including actions and related objects and it all seems correct.
Object creation and share action
// ############## OpenGraph - Arrive At a Marina
// Photo
var photoURL = ""
if let image = firstMarina.images.first {
photoURL = image.width1440
} else {
photoURL = "https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png"
}
let photo = FBSDKSharePhoto(imageURL: NSURL(string: photoURL)!, userGenerated: false)
// Properties
let properties = [
"fb:app_id": "xxxxxxxxxxxxxxxxxxxxx",
"og:locale": NSLocale.preferredLanguages()[0].stringByReplacingOccurrencesOfString("-", withString: "_"),
"og:type": "smartsea:marina",
"og:title": firstMarina.name!.text,
"og:description": firstMarina.desc!.text,
"og:image": [photo],
"place:location:latitude": firstMarina.location!.lat,
"place:location:longitude": firstMarina.location!.lng
]
// Object
let object = FBSDKShareOpenGraphObject(properties: properties as [NSObject : AnyObject])
// Action
let action = FBSDKShareOpenGraphAction(type: "smartsea:arrive_at", object: object, key: "marina")
// Content
let content = FBSDKShareOpenGraphContent()
content.action = action
content.previewPropertyName = "marina"
// Share
FBSDKShareDialog.showFromViewController(self, withContent: content, delegate: self)
and the error returned
Error Domain=com.facebook.Facebook.platform Code=102 "(null)" UserInfo={error_reason=The content you're trying to share includes a link that our security systems detected to be unsafe:
https://m.facebook.com/appcenter/smartsea?fbs=9909&fb_object_id=1684374595135519
Please remove this link to continue., error_description=An error occurred during publishing., app_id=xxxxxxxxxxxxxxxxxxxxx, error_code=102}
The strange thing is that the error URL is a Facebook domain and I haven't share it this URL directly. It seems to be generated with every share action.
Any idea?
Thanks!
Unfortunately I can't post a simple comment, so I have to post it as an 'answer'. I have found this article. It's about blocked URLs, but unfortunately not about blocked 'Facebook' URLs. I hope it can help.
http://www.technerves.com/2015/07/unblock-your-website-url-from-facebook.html
It connection might be getting blocked due to App transport security. App transport security is a new thing introduced in iOS9.
It blocks connections to servers that don't meet certain security requirements, such as minimum TLS version etc
Please try again after turning ATS OFF from info.plist. See this link which shows how to turn ATS OFF.
I'm working on project first time with swift language. I have used alamofire for web service api. I have created a common func for it.
class func postWebService(methodname:String,param:NSDictionary,userName:String,password:String, CompletionHandler:(success:Bool,response:NSDictionary) -> ())
{
let mainlink :String = "mymainurl"
var link = mainlink + methodname
var url:NSURL = NSURL(string: link)!
let plainString = "\(userName):\(password)" as NSString
// example : let plainString = "textuser:testpwd" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]
request(.GET, url, parameters: param as? [String : AnyObject]).responseJSON { (req, res, jsonresp, error) -> Void in
if(error != nil) {
NSLog("Error: \(req) \(error)")
var errDict:NSDictionary = ["message":"\(error?.localizedDescription)"]
CompletionHandler(success: false,response: errDict)
}
else {
var json: NSDictionary = jsonresp! as! NSDictionary
NSLog("%#",json)
CompletionHandler(success: true,response: json)
}
}
}
It is working fine and gives me response when I run it in simulator. But if I load my project in device than It gives me a error
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x17dc4580 {NSDebugDescription=Invalid value around character 0.})
If there is a problem in code than it should not work in simulator also. And it is nice and working code for web service api. Any help will be appreciated. Thanks in advance.
==== EDIT====
Mention : it is server url.
I figured out one more thing. If I run this code in ios 8 and above device it is working fine. And this problem is occurred in ios 7 device. I'm dealing with iPod with ios7. I have checked in ios8 devices like iPhone and iPad, it is working fine.
May or not be the case with you but I once had that error when accessing a url that was not correct. In my case it was pointing to localhost, which was perfect for the simulator but complete useless on the device.
Double check your URL, make sure the web service is online and can be reached from your device...
Hope this helps, if not others will chime in ;)
I have researched for this and mainly I checked all information of Alamofire on github. In this page I have found solution and it is my main and big mistake is that Alamofire have not support of ios 7. It Requires ios 8+.
Above My code is right and good for web service api. There is no problem in URL or in Code. My problem is for ios 7.0 which is not supported so this problem occured.
So, It is my own mistake, not of Alamofire Framework or code. But is should support ios7 because we can't ignore ios version 7 for our projects. There are may be lots of devices having ios7. Thanks for all support.
I'm fairly new to Swift and iOS development in general. My app has a model that can easily be expressed as comma separated values (csv), so naturally I want the user to be able to export the data as an csv file and opening that file in another application. Since I didn't find any examples in Swift, I gave it a try on my own:
func ExportToCSV(delegate: UIDocumentInteractionControllerDelegate){
let fileName = NSTemporaryDirectory().stringByAppendingPathComponent("myFile.csv")
let url: NSURL! = NSURL(fileURLWithPath: fileName)
var data = "Date,Time,Count\n2014-11-21,14.00,42"
data.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
if url != nil {
let docController = UIDocumentInteractionController(URL: url)
docController.UTI = "public.comma-separated-values-text"
docController.delegate = delegate
docController.presentPreviewAnimated(true)
}
}
(the delegate parameter is the view that calls the function, as in MyClass.ExportToCSV(self))
This works, mostly, and I see the following views:
However, in the Simulator I get the following warning:
Unbalanced calls to begin/end appearance transitions for <QLRemotePreviewContentController: 0x7fcd720da800>.
as well as
Unknown activity items supplied: ("<QLPrintPageRenderer: 0x7fcd73861ee0>","<UIPrintInfo: 0x7fcd714b9030>")
when I click the action button, then after a while
Communications error: <OS_xpc_error: <error: 0x10e032b10> {
count = 1, contents = "XPCErrorDescription"
=> <string: 0x10e032f18> { length = 22, contents = "Connection interrupted" }
}>
and when I click Mail there is a crash with the following error:
viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain
Code=3 "The operation couldn’t be completed. (_UIViewServiceInterfaceErrorDomain error 3.)"
UserInfo=0x7fcd71631460 {Message=Service Connection Interrupted}
<MFMailComposeRemoteViewController: 0x7fcd73864aa0> timed out waiting for fence
barrier from com.apple.MailCompositionService
Although on the actual device everything works as planned, so many errors throw me off a bit. Is there a better solution?
This is probably due to objects already have been deallocated when they are accessed by the mail or printing app. Try to declare your docController and url variables as class properties so they keep alive as long as the view controller exists.