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])
Related
I was reviewing "old" code (not that old, but a developer went away and we are documenting and reviewing his code), when, in the context of a iOS Share Extension, I found the following two lines:
let content = self.extensionContext!.inputItems[0] as! NSExtensionItem
for attachment in content.attachments as! [NSItemProvider] {
The first line: I red the docs and found inputItems can be empty too, so I suppose that forced cast will crash the app if this thing should happen (I don't know exactly how, but maybe it could).
The second line: same as above, with the difference that if you have no crash in the first line you probably won't have another here.
Question 1: is it a good idea to check the length of inputItems before the loop?
Question 2: I made a little edit to this code and I changed the first line to this:
let content = self.extensionContext!.inputItems[0] as? NSExtensionItem
After doing so, XCode suggests a correction to the second line I don't like very much (I consider it not readable):
for attachment in (content?.attachments as? [NSItemProvider])!
is the XCode suggestion the way to go?
Any comment is appreciated. Thanks!
It's always a good idea to unwrap optionals before accessing the object itself.
You can use guard to unwrap the optional chain before proceeding to work with the content.
guard let content = self.extensionContext?.inputItems.first as? NSExtensionItem else { return }
guard let attachments = content.attachments as? [NSItemProvider] else { return }
for attachment in attachments {
// Do stuff
}
Resources:
Statements
Patterns
You might want to review the documentation for Swift optionals
Forced unwrapping will crash the app when encountering nil values which are different from empty arrays.
Question 1: No, you don't have to, for-in loops account for the length of the array. Also, the code will loop over content.attachments not inputItems.
Question 2: Your edit of the first line caused content to become an optional value, requiring some kind of unwrapping in the second line
If you can be sure the casts will always work the way your developer had it is fine. If you want more safety I would probably do:
guard let content = self.extensionContext?.attachments.first as? NSExtensionItem,
let attachments = content.attachments as? [NSItemProvider] else
{
// fatalError()
return
}
for attachment in attachments
{
//
}
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.
I'm just starting developing apps with Swift 2.0, and as I'm working having problem with initiating a variable with the value of a text field in my app.
this is the function I'm having problems with. It's called when a button under the text field is pressed as submit.
#IBAction func checkName(sender: AnyObject) {
guard let name : String = nameField.text else { print("Name not valid.");return}
let checker = NameChecker()
let result = checker.nameChecker(name)
print(result)
}
this only thing this code returns on the XCode shell is "lldb". I also tried to use the debugger to figure out where I was messing up but unfortunately I found out that was harder than expected and I wasn't able to.
If you have any idea why my code is only returning "lldb" I would really appreciate is you could let me know since I've been experiencing this error quite often lately.
I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}
Hi I am really new to coding in Swift, and am trying to follow the codes in this book: http://www.apress.com/9781484202098. Learn iOS 8 App Development 2nd Edition by James Bucanek
In particular, I am working through Chapter 3 - building a URL shortening app, but despite having copied the code exactly, I am getting an error on the code in Page 76:
if let toShorten = webView.request.URL.absoluteString {
which states 'NSURLRequest?' does not have a member named 'URL'.
I have tried googling an answer, but unfortunately have not come across anything. Any response I can find seems to suggest that my code ought to be working (e.g. How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? but the solution does not appear to work for me. If I add a ? after the request, it will then at least build it, but I then have a nil variable returned.
I am using Xcode v6.1.1. Here is the piece of code that is coming up with the error in ViewController.swift:
let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
var shortenURLConnection: NSURLConnection?
var shortURLData: NSMutableData?
#IBAction func shortenURL( AnyObject ) {
if let toShorten = webView.request?.URL.absoluteString { // ? now added
let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) //added if here and removed !
let request = NSURLRequest(URL:firstrequest)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
If you have any suggestions on how I can fix this, I would really appreciate it!
Update:
Following suggestions from Ashley below, I have amended my code so that it is no longer bringing up the error (see comments above). However, it is now no longer running. This appears to be because the urlString is being created as http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/"). The problem is therefore the Optional() that is included and thus makes it an invalid URL. Does anyone have a suggestion on how to remove this please?
request is an optional property on UIWebView:
var request: NSURLRequest? { get }
also stringByAddingPercentEscapesUsingEncoding returns an optional:
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
What you need is to make user of optional binding in a few places:
if let toShorten = webView.request?.URL.absoluteString {
if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) { // If a method can return a nil, don't force unwrap it
let request = NSURLRequest(URL:first request)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
See Apple's docs on optional chaining for details
See Apple's docs for NSURL class