0

I'm trying to send data through URL but some data at all time is not have value because the user doesn't change it so I give it empty string.

if the user not change it but when I'm executing code I put breakpoints at each important line and the error "unexpectedly found nil while unwrapping an Optional value" appears in this line

 let postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData

post like this:

username=myusername&password=&tel=&email=myemail&address=&DOB=choose&cinsiyet=2&changedPass=false

Tel,password and address doesn't have value(or it's empty string) because the user doesn't change it.

The encoding of String can affect in this case or what because all not changed textfield have "" ( empty String ) and I'm sure from that.

Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
Samah Ahmed
  • 419
  • 8
  • 24

2 Answers2

3

You are force-unwrapping the result of post.data(using:). If the conversion to Data fails (for example if post has an other encoding than you are using), it returns nil and will make your code crash.

Generally, I would recommend you to never use force-unwrapping (!) or force-casting as!, if you are not 1000% sure that it will succeed. Instead, you should use a guard let statement:

guard let postData = post.data(using: String.Encoding.ascii) else {
    //an error occurred
    return
}

Additionally, in Swift 3, we do not use NSData. Use Data instead.

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
0

I solved that, by putting if statement for one textfield that may take 3 value.

Samah Ahmed
  • 419
  • 8
  • 24