简体   繁体   English

尝试在 iPhone 上复制文本时应用程序崩溃

[英]App crashes when trying to copy text on iPhone

I program an "encryption app" that encrypts texts in a simple way.我编写了一个“加密应用程序”,以一种简单的方式加密文本。 This is the code:这是代码:

let smallLetters: String = "abcdefghijklmnopqrstuvwxyz"
let bigLetters: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

let input: String = encryptTextField.text!
    
    encryptTextField.text! = ""
    
    var value: String = ""
    
    for c in input {
        let otherChars: String = " !§$%&/()=?´`#+'*-_.:,;<>^°@€{}≠¿|][¢¶“¡≤≈ç√∫~µ@€öäüÜÖÄ"
        
        for i in otherChars {
            if c == i {
                value += String(i)
                print("i")
            }
        }
        
        var dCount: Int = 0
        var eCount: Int = 0
        
        var dFound: Bool = false
        var eFound: Bool = false
        
        for d in smallLetters {
            if !dFound {
                if c == d {
                    dFound.toggle()
                    
                    let y: Int = smallCount - dCount
                    var z: Int = 1
                    
                    for i in smallLetters {
                        if y == z {
                            print("[\(c) -> \(i)]")
                            value += String(i)
                        }
                        
                        z += 1
                    }
                } else {
                    dCount += 1
                }
            }
        }
        for e in bigLetters {
            if !eFound {
                
                if c == e {
                    eFound.toggle()
                    
                    let y: Int = bigCount - eCount
                    var z: Int = 1
                    
                    for i in bigLetters {
                        if y == z {
                            print("[\(c) -> \(i)]")
                            
                            value += String(i)
                        }
                        
                        z += 1
                    }
                } else {
                    eCount += 1
                }
            }
        }
    }
    
    let maximumChars: Int = 15
    
    var string: String = ""
    var i: Int = 1
    
    var b: Bool = false
    
    for c in value {
        if !b {
            if i <= maximumChars {
                string += String(c)
            } else {
                string += "..."
                b = true
            }
            
            i += 1
        }
    }
    
    let alert: UIAlertController = UIAlertController(title: "Encoded!", message: "Your input is now encrypted / decrypted.", preferredStyle: UIAlertController.Style.alert)
    let cancel: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: { (alert: UIAlertAction!) in
        self.encryptTextField.text! = value
        print("OK")
        
        self.encryptTextField.placeholder = "Enter a text to encrypt..."
    })
    let copy: UIAlertAction = UIAlertAction(title: "Copy!", style: UIAlertAction.Style.default, handler: { (alert: UIAlertAction!) in
        print("Copy!")
        
        let pasteboard: UIPasteboard = UIPasteboard.general
        pasteboard.string! = value
        
        self.encryptTextField.placeholder = "'" + string + "' was copied!"
    })
    
    alert.addAction(cancel)
    alert.addAction(copy)
    
    present(alert, animated: true, completion: nil)

So that I can quickly insert the encrypted text into another app (eg WhatsApp) I use this code (simplified):这样我就可以快速将加密文本插入另一个应用程序(例如 WhatsApp),我使用以下代码(简化):

let pasteboard: UIPasteboard = UIPasteboard.general
pasteboard.string! = "Hello World!"

The code works in the simulator: The encrypted text is copied and I can paste it with a double click (see picture).该代码在模拟器中工作:加密文本被复制,我可以通过双击粘贴它(见图)。

Paste encrypted text with a double click双击粘贴加密文本

But when I run the app on my mobile phone (iPhone 8), the app crashes at this point!但是当我在手机(iPhone 8)上运行应用程序时,应用程序此时崩溃了!

Does anyone know a solution or at least know why?有谁知道解决方案或至少知道为什么?

The solution here is to not force unwrap optional variables in your code.这里的解决方案是不要强制解开代码中的可选变量。
I highly recommend to read more about Optionals in Swift here .我强烈建议在这里阅读更多关于 Swift 中的 Optionals 的信息。

let input: String = encryptTextField.text!
The text in a UITextField can be nil. UITextField 中的文本可以为 nil。 The data type is a String optional( String? )数据类型是可选的字符串( String?

Instead of the above, use if let statements to safely unwrap optionals!而不是上面的,使用if let语句来安全地解开可选项!

if let input = encryptTextField.text{
   // Your logic/code to process input as String goes here
}

Similarly, You can remove the force unwrapping(".") done here.同样,您可以删除此处完成的强制展开(“。”)。
1. encryptTextField.text! = "" 1. encryptTextField.text! = "" encryptTextField.text! = "" . encryptTextField.text! = "" Just use encryptTextField.text = ""只需使用encryptTextField.text = ""
2. pasteboard.string! = value 2. pasteboard.string! = value pasteboard.string! = value You can remove the force unwrapping(".") done here. pasteboard.string! = value您可以删除此处完成的 force unwrapping(".") 。
3. pasteboard.string! = "Hello World!" 3. pasteboard.string! = "Hello World!" pasteboard.string! = "Hello World!"

Basically only force unwrap variables if you for sure know that the value that the optional variable holds is not nil!基本上只有在你确定知道可选变量所持有的值不是 nil 的情况下才强制解包变量!

Force unwrapping optional variables that hold a nil value will crash you app!强制解包包含 nil 值的可选变量将使您的应用程序崩溃!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM