While profile updation getting error in swift using Alamofire? - ios

I am using Alamofire to update the profile through .GET method. If I use any space in any field between characters on any field its has error fatal error: unexpectedly found nil while unwrapping an Optional value.But the same URL working fine if I test it on Postman, successfully updated. so through application why it is creating error in Alamofire .
#IBAction func btnSavePressed(sender: AnyObject) {
Firstname = txtFName.text!
Lastname = txtLname.text!
Username = txtUname.text!
Phone = Int(txtPhone.text!)
DoorNo = txtDoorNo.text!
Street = txtStreet.text!
Town = txtTown.text!
Postcode = Int(txtPostCode.text!)
print(Firstname)
print(Lastname)
print(Username)
print(Phone)
print(DoorNo)
print(Street)
print(Town)
print(Postcode)
print("http://\(platform).eposapi.co.uk/?app_id=\(apiID)&app_key=\(apikey)&request=\(request)&id=\(UserID)&fname=\(Firstname)&lname=\(Lastname)&phone=\(Phone)&dno=\(DoorNo)&add1=\(Street)&add2=\(Town)&postcode=\(Postcode)")
UPDATE_data_from_URl()
}
func UPDATE_data_from_URl(){
Alamofire.request(.GET, "http://\(platform).eposapi.co.uk/?app_id=\(apiID)&app_key=\(apikey)&request=\(request)&id=\(UserID)&fname=\(Firstname)&lname=\(Lastname)&phone=\(Phone)&dno=\(DoorNo)&add1=\(Street)&add2=\(Town)&postcode=\(Postcode)", parameters: nil )
.responseJSON {
response in
print(response)
if let result: AnyObject = response.result.value {
let post: JSON = JSON(result)
let action = post["action"].boolValue
let info = post["info"].stringValue
print(action)
print(info)
if action == false{
let alert = UIAlertController(title: "", message: info, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
else{
let alert = UIAlertController(title: "Success", message: info, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){
(action) in
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("yourtabbarvcidentifier") as! UITabBarController
vc.selectedIndex = 0
self.revealViewController().pushFrontViewController(vc, animated: true)
})
self.presentViewController(alert, animated: true, completion: nil)

Need to remove white space from your string then try it.
let linkString = "http://maps.google.com/maps?q=\(Location!)"
let address = NSURL(string:linkString.stringByReplacingOccurrencesOfString(" ", withString: ""))!

Related

iOS App Crashes on every device except devices connected with Xcode

My app crashes and quit when user try to register a new account but that occurs on any device except devices deployed the app with Xcode.
All the devices are registered in the developer account and running iOS 11.4.1
Here is the register button function:
#IBAction func regButton(_ sender: Any) {
usernameText = usernameTextField.text
mobileText = mobileTextField.text
emailText = emailTextField.text
passwordText = passwordTextField.text
fieldText = categoryTextField.text
print(usernameText ?? "damn")
print(mobileText ?? "damn")
print(emailText ?? "damn")
print(passwordText ?? "damn")
print(fieldText ?? "damn")
if(type=="Seeker")
{
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_jobseeker?name="+usernameText!+"&phone="+mobileText!
let url2 = "&email="+emailText!+"&password="+passwordText!+"&workex="+"companyDescText!"
let url3 = "&category="+fieldText!+"&image="+"downloadURLGlobal!"
let url4 = "&unpaidhour="+"string"+"&hourpaidlast30="+"string"+"&totalhourworked="+"string"+"&balance="+"string"+"&username="+usernameText!
stringURL = url1 + url2 + url3 + url4
}else
{
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_company?name="+usernameText!+"&field="+fieldText!
let url2 = "&phone="+mobileText!+"&email="+emailText!+"&password="+passwordText!+"&workex="+"companyDescText!"+"&crcopy="+"downloadURLGlobal!"+"&logo="+"string"+"&username="+usernameText!
stringURL = url1 + url2
}
if Reachability.isConnectedToNetwork()
{
if(checkbox.on==true)
{
let url = URL(string: stringURL!)
Alamofire.request(url!).responseString {
(response) in
let result = response.result.value
do {
if(result=="True")
{
let alert = UIAlertController(title: "Registration Successfully", message: "Registration Done Successfully Congratulations",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style:
UIAlertActionStyle.default, handler: self.doSomething))
self.present(alert, animated: true, completion: nil)
}else
{
let alert = UIAlertController(title: "Registration Failed", message: "Registration Failed Please Try Again", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
}else
{
let alert = UIAlertController(title: "License Agreement", message: "Check to Agree Licence Agreement", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}else
{
let alert = UIAlertController(title: "No Network Connection", message: "Connection Error Please Try Again", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
If a user will tap the button but one or both text fields are empty then your app will crash due to forced unwraping (! mark) which you use in your code.
Example: if mobileText field will be empty then the your app will crash:
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_jobseeker?name="+usernameText!+"&phone="+mobileText!
the solution is to use guard statement
guard let usernameText = usernameTextField.text,
mobileText = mobileTextField.text,
emailText = emailTextField.text,
passwordText = passwordTextField.text,
fieldText = categoryTextField.text else {
return
}

Swift 4 local variable value assignment

I am trying to recovery a value from firebase database and compare it with a UITextField value, in case of matching, I save it to a var that I will us. The problem is that the variable in question has a default value just when I use it.
Above I show my func code where the variable affected is "codeRecovered":
#IBAction func signUpAction(_ sender: AnyObject)
{
var codeRecovered: String = ""
if emailSignUpTextField.text == "" || self.secretCodeTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email, pin code and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else {
self.dbHandler = self.ref?.child("Companies").observe(.value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let value = snap.value as! [String:String]
if let auxSecretCode = value["secretCode"]
{
if auxSecretCode == self.secretCodeTextField.text{
print("Value recovered OK(works fine): \(auxSecretCode)")
codeRecovered = auxSecretCode
print("Recovered value saved OK(works fine): \(codeRecovered)")
}
}
}
})
//Here codeRecovered is already ""
print("\(codeRecovered) is the recovered value(empty) and \(self.secretCodeTextField.text ?? "def") is the textField value")
if codeRecovered != self.secretCodeTextField.text{
let alertController = UIAlertController(title: "Error", message: "Please enter a correct pin code", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
//....
Async calls with sync result use....
#IBAction func signUpAction(_ sender: AnyObject)
{
var codeRecovered: String = ""
if emailSignUpTextField.text == "" || self.secretCodeTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email, pin code and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else {
self.dbHandler = self.ref?.child("Companies").observe(.value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let value = snap.value as! [String:String]
if let auxSecretCode = value["secretCode"]
{
if auxSecretCode == self.secretCodeTextField.text{
print("Value recovered OK(works fine): \(auxSecretCode)")
codeRecovered = auxSecretCode
print("Recovered value saved OK(works fine): \(codeRecovered)")
}
}
}
//Here codeRecovered is already ""
print("\(codeRecovered) is the recovered value(empty) and \(self.secretCodeTextField.text ?? "def") is the textField value")
if codeRecovered != self.secretCodeTextField.text{
let alertController = UIAlertController(title: "Error", message: "Please enter a correct pin code", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
})
to use your codeRecovered in a sequence it must be within self.dbHandler = self.ref?.child("Companies").... block because it runs in async thread

“Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)”?

This is my swift code
i will get above error on this line : guard (newUser["status"] as! Int != 0)
#IBAction func signInButton(_ sender: UIButton) {
if validator(){
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
let datas:[String:String] = ["email":self.emailField.text!,"name": self.nameField.text!,"password" : self.passwordField.text!]
DispatchQueue.main.async {
SwiftSpinner.show("Signin' in...")
}
let newUser:NSDictionary = self.marketcloud!.createUser(datas)
print(newUser)
DispatchQueue.main.async {
SwiftSpinner.hide()
guard (newUser["status"] as! Int != 0) else {
let alertController = UIAlertController(title: "Error", message: "Email already in use. Try with a different one!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Close",
style: UIAlertActionStyle.destructive,
handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}
let alertController = UIAlertController(title: "Ok!", message: "User created successfully!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
UserData.setLastRegisteredUser(self.emailField.text!, password: self.passwordField.text!);
print("Setted UserData \n \(UserData.getLastRegistedUserEmail(),UserData.getLastRegisteredUserPassword())")
//returns to the login view
let next = self.storyboard!.instantiateViewController(withIdentifier: "viewController") as! ViewController
next.downloadProducts = false
next.load = true
self.navigationController?.pushViewController(next, animated: true)
}));
self.present(alertController, animated: true, completion: nil)
}
})
}
}
Try to understand how guard works.
The condition must be an optional binding with let or a boolean expression
guard let status = newUser["status"] as? Int, status != 0 else { ...
And no parentheses in Swift.

UIViewController failing to navigate to another page in swift

I have previously written this function and it was working fine. I started working on the project again after a week's break and the same code is not working. Am I missing something here? Basically if a button is pushed, checkCredentials will run. Everything in the "else" section is working completely fine, but the if user != nil section isn't working:
func checkCredentials (){
PFUser.logInWithUsernameInBackground(usernameLoginTxt.text!, password: passwordLoginTxt.text!){
(user:PFUser?, error:NSError?) -> Void in
if user != nil{
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("SearchViewController") as UIViewController
self.presentViewController(vc, animated: false, completion:nil)
NSLog("it was successfull dude")
}else{
let title = "Warning!"
let message = "You have entered the wrong username or password.\n Please try again!"
let okButton = "Ok"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayButton = UIAlertAction(title: okButton, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okayButton)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
This should work for you...
func login(){
let user = PFUser()
user.username = userNameText.text
user.password = passwordText.text
PFUser.logInWithUsernameInBackground(userNameText.text!, password: passwordText.text!, block: {
(user: PFUser?, Error: NSError?) -> Void in
if Error == nil {
dispatch_async(dispatch_get_main_queue()) {
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let AfterLoginVC: UIViewController = Storyboard.instantiateViewControllerWithIdentifier("AfterLoginVC") as! UINavigationController
self.presentViewController(AfterLoginVC, animated: true, completion: nil)
}
} else {
let title = "Warning!"
let message = "You have entered the wrong username or password.\n Please try again!"
let okButton = "Ok"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayButton = UIAlertAction(title: okButton, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okayButton)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
Also be sure that over the last week you didn't accidentally change your Parse client key (I've done that before) which will cause it to not show any error but simply to not work.

stop animating ActivityViewIndicator after invalid login

I'm new to iOS programming and currently is playing around with some tutorial found online. I was trying to include an ActivityViewIndicator in the sign in view. When the "Sign In" button is tapped, an ActivityViewIndicator should show up and it show be hidden when sign in is invalid. My problem is where should i put the self.signInViewIndicator.stopAnimating(); when the sign in is invalid? I have enabled the Hides When Stopped option.
#IBAction func SignInButtonTapped(sender: AnyObject) {
let userUsername = userUsernameTextField.text
let userPassword = userPasswordTextField.text
if(userUsername.isEmpty || userPassword.isEmpty) { return}
signInViewIndicator.startAnimating()
// Send user data to server side
let myUrl = NSURL(string: "http://192.168.168.135:8080/userLogin.php")
let request = NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod = "POST"
let postString = "username=\(userUsername)&password=\(userPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
println("result: \(resultValue)")
var isUserSignedIn:Bool = false
if(resultValue=="Success") {
isUserSignedIn = true
// Login is successful
NSUserDefaults.standardUserDefaults().setBool(isUserSignedIn, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
self.signInViewIndicator.stopAnimating()
var messageToDisplay:String = parseJSON["message"] as! String!
if(!isUserSignedIn)
{
messageToDisplay = parseJSON["message"] as! String!
}
dispatch_async(dispatch_get_main_queue(), {
// Display alert message with confirmation
var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
}
}
task.resume()
}
You almost got it rigth, you can never update the UI from a thread other than the main thread, as you was already displaying the alert in the main thread I just had to move your message "self.signInViewIndicator.stopAnimating()" to inside that dispatch block:
dispatch_async(dispatch_get_main_queue(), {
// Display alert message with confirmation
self.signInViewIndicator.stopAnimating()
var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
})

Resources