ina patodiya ina patodiya - 5 months ago 9
Swift Question

How to convert this to Swift

- (IBAction) btnSaveToTemplatePressed:(id)sender
{
if([_tfMessage.text isEqualToString:@""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""message:@"Please enter message." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}

NSUserDefaults *uDefault=[NSUserDefaults standardUserDefaults];
NSMutableArray *templates = [NSMutableArray arrayWithArray:[uDefault arrayForKey:@"TEMPLATES"]];
if(![templates containsObject:_tfMessage.text])
{
[templates addObject:_tfMessage.text];
[uDefault setObject:templates forKey:@"TEMPLATES"];
[uDefault synchronize];
}

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success"message:@"Template saved." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


here i gave code in objective c. i please any one give me its swift conversion because i want it. here on click this button my data saved in template and show also in that.

Answer

Use this because answer posted by Tarvo may give some errors at run time because the link of the website attached is not converting to the updated Swift 2.2

@IBAction func btnSaveToTemplatePressed(sender: AnyObject) {
    if (tfMessage.text == nil || tfMessage.text == "") {
        let alert: UIAlertView = UIAlertView(title: "", message: "Please enter message.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
        alert.show()
        return
    }
    let uDefault: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    var templates: [String] = [String]()
    if let arr = uDefault.arrayForKey("TEMPLATES")
    {
        templates.appendContentsOf(arr as! [String])
    }

    if templates.contains(tfMessage.text!) {
        templates.append(tfMessage.text!)
        uDefault.setObject(templates, forKey: "TEMPLATES")
    }
    let alert: UIAlertView = UIAlertView(title: "Success", message: "Template saved.", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
    alert.show()
}