I need to manage mailto protocol with this string:
mailto:sales#myweb.co.uk?subject=Something%20from%20Random%20Thing%20app
I'm doing with this code:
if parameter.hasPrefix("mailto") {
let urlString = parameter.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
if let url = URL(string: urlString ?? ""), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
} else {
let alert = UIAlertController(title: L10n.error, message: L10n.notSupportEmail, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
SectionManager.sharedInstance.navigationController?.topViewController?.present(alert, animated: true, completion: nil)
}
}
When the mail app is opened, the subject still contains the "%20" encoded spaces.
How can this be avoided?
Related
I want to show an alert to users via UIAlertController when my app can't open a URL. Here's my code:
guard let url = URL(string: urlLink) else {
return
}
UIApplication.shared.open(url, options: [:])
And my created alert:
let alert = UIAlertController(title: "Warning", message: "Problem with URL.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
If I move my alert inside the guard statement, it never occurs. I tested it by changing urlLink to some random String, for example, "123". Any ideas of how I can show an alert?
EDIT:
I used canOpenURL which return Bool. Now my code is:
guard let url = URL(string: urlLink) else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
} else {
let alert = UIAlertController(title: "Warning", message: "Problem with URL.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
Should be before return
guard let url = URL(string: urlLink) , UIApplication.shared.canOpenURL(url) else {
let alert = UIAlertController(title: "Warning", message: "Problem with URL.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
return
}
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
}
I am new to swift . I have developed a login form which verifies data from mysql database and for that I have used json and swift code . But there is an issue in my code , after providing the login details when I click on the submit button .It shows the alert view that the credentials are invalid ,even after providing the correct credentials . I have attached the code below . Please if anyone can help me
class ViewController: UIViewController {
#IBOutlet weak var PASSWORD: UITextField!
#IBOutlet weak var USERNAME: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func submitbtn(_ sender: Any) {
let username: NSString = self.USERNAME.text! as NSString
let password: NSString = self.PASSWORD.text! as NSString
if username.isEqual(to: "") || password.isEqual(to: ""){
let myAlert = UIAlertController(title: "Alert", message:"All fields are required to fill in", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
// return
}
else
{
let post:NSString = "UserName\(username)&PassWord\(password)" as NSString
NSLog("PostData : %d", post)
let url = "http://demo.talentclouds.in/API/LoginHandler.asmx/Login?username=admin#penn.in&password=123"
let postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
let postLength:NSString = String ( postData.length ) as NSString
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoder", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
// let responseError:NSError?
// let response:URLResponse?
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
DispatchQueue.main.async {
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
//parsing the response
do {
//converting resonse to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let username = parseJSON["username"] as? String
if(username != nil)
{
UserDefaults.standard.set(parseJSON["username"], forKey: "username")
UserDefaults.standard.set(parseJSON["password"], forKey: "password")
UserDefaults.standard.synchronize()
// let username : NSInteger = json?.value(forKey: username as String)as! NSInteger
// NSLog("Success : %ld ", username)
// if (username != nil)
// {
print("Login OK")
}
else{
print("Login Failed")
let alert = UIAlertController(title: "Invalid", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
catch {
print("Login Failed")
let alert = UIAlertController(title: "Error", message: "Please check your internet connection", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
//executing the task
task.resume()
}
}
}
Your issue there
let username = parseJSON["username"] as? String
It should be read profile dictionary first
if let profile = parseJSON["Profile"] as? [String:Any],
let username = profile["username"] as? String
Here Full code:
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
DispatchQueue.main.async {
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
//parsing the response
do {
//converting resonse to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if let profile = parseJSON["Profile"] as? [String:Any],
let username = profile["username"] as? String
{
UserDefaults.standard.set(parseJSON["username"], forKey: "username")
UserDefaults.standard.set(parseJSON["password"], forKey: "password")
UserDefaults.standard.synchronize()
// let username : NSInteger = json?.value(forKey: username as String)as! NSInteger
// NSLog("Success : %ld ", username)
// if (username != nil)
// {
print("Login OK")
}
else{
print("Login Failed")
let alert = UIAlertController(title: "Invalid", message: "Invalid Credentials", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
catch {
print("Login Failed")
let alert = UIAlertController(title: "Error", message: "Please check your internet connection", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
})
//executing the task
task.resume()
}
}
}
I've this code to take the X-Transmission-Session-Id but now i need to resend the request with the updated header.
function takeXTransmissionSessionId( ){
let urls = NSURL(string: "\(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(urls!) { (data, respornse, error) -> Void in
guard error == nil && data != nil else {
print("error=\(error!)")
let alertView = UIAlertController(title: "ERROR", message: "A server with the specified hostname could not be found.", preferredStyle: UIAlertControllerStyle.Alert)
let actionView = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertView.addAction(actionView)
self.presentViewController(alertView, animated: true, completion: nil)
return
}
if let httpStatus = respornse as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
let sesionID = httpStatus.allHeaderFields["X-Transmission-Session-Id"]
if sesionID == nil {
let alertView = UIAlertController(title: "ERROR", message: "The request has not been applied because it lacks valid authentication credentials for the target resource.", preferredStyle: UIAlertControllerStyle.Alert)
let actionView = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertView.addAction(actionView)
self.presentViewController(alertView, animated: true, completion: nil)
}else{
//print("\(respornse!)")
//print("\(sesionID!)")
self.XTransmissionSessionId = "\(sesionID!)"
}
}
}
task.resume()
}
My problem is i tray many times in a different ways but i don't know what i need to do.
Thanks!
This is the code for do what i need:
request.HTTPMethod = "POST"
request.addValue("\(XTransmissionSessionId)", forHTTPHeaderField: "X-Transmission-Session-Id")
I have a UIAlert that notifies the user that they do not have an internet connection and that they need one in order to use the app. As well as letting them dismiss the alert by tapping the ok action I also want to have a action that when tapped takes the user to the settings app.
func displayAlert(title: String, message: String){
var formEmpty = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
formEmpty.addAction((UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in
})))
Use this code . May be help it.
override func viewDidAppear(animated: Bool) {
var alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .Alert)
var settingsAction = UIAlertAction(title: "Settings", style: .Default) { (_) -> Void in
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.sharedApplication().openURL(url)
}
}
var cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil);
}
Please note UIApplicationOpenSettingsURLString is only available on iOS8.0 and after so if your app should support iOS7 you'll have to check for availability of the constant (or if using Swift 2.0 use the #availability keyword).
You can navigate to the setting with this code:
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(settingsUrl!)
After adding this code in your function your function will look like:
func displayAlert(title: String, message: String){
var formEmpty = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
formEmpty.addAction((UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in
//This will call when you press ok in your alertview
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(settingsUrl!)
})))
}
For iOS 10, Swift 3:
let alert = UIAlertController(title: "Alert!", message: "your message here", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.shared.open(settingsUrl as! URL, options: [:], completionHandler: nil)
alert.addAction(settingsAction)
present(alert, animated: true, completion: nil)