简体   繁体   English

当图片不存在时崩溃保存我的个人资料iOS

[英]crash saving my profile when image don't exist iOS

I'm having some trouble when I press the button save to edit the profile : 按下保存按钮以编辑配置文件时遇到麻烦:

for example the image don't exist and when I press save button, it's crash, please find below my code? 例如图片不存在,当我按保存按钮时,它崩溃了,请在我的代码下面找到? what am I missing ? 我想念什么?

Once I remove the condition if the profile image don't exist my code work.. 一旦我删除条件(如果个人资料图片不存在),我的代码就会工作。

  let profileImageData = UIImageJPEGRepresentation(imageUser.image!, 0.0) //--------------------------------------- // Check if all fields are empty //--------------------------------------- if (Name.text!.isEmpty && Username.text!.isEmpty && website.text!.isEmpty && aboutUser.text!.isEmpty && emailUser.text!.isEmpty && phoneUser.text!.isEmpty && genderUser.text!.isEmpty && (profileImageData == nil)) { print("error") } 

You are force unwrapping the contents of the variable imageUser.image in the first line of code you posted. imageUser.image在发布的第一行代码中强制展开变量imageUser.image的内容。 When you do this, it will crash your application if the value of imageUser.image is nil . 执行此操作时,如果imageUser.image值为nil ,它将使您的应用程序崩溃。 I suggest you check out the section on Optionals in The Swift Programming Language (Swift 2.0) . 我建议您查看有关Swift编程语言(Swift 2.0)中的 Optionals的部分。

If imageUser.image can be nil, this is a more correct version of your code. 如果imageUser.image可以为nil,则这是代码的更正确版本。 Note the use of an if let statement to safely unwrap the contents of imageUser.image . 请注意,使用if let语句可以安全地包装imageUser.image的内容。 It's worth mentioning that every place you're using a ! 值得一提的是,您正在使用的每个地方! in your code below, will crash if that value you're using it on is nil (which is why this code only more correct and not fully correct). 在下面的代码中,如果您使用的值是nil ,则将崩溃(这就是为什么此代码更正确而不完全正确的原因)。

if let profileImage = imageUser.image {
    let profileImageData = UIImageJPEGRepresentation(profileImage, 0.0)

    //---------------------------------------
    // Check if all fields are empty
    //---------------------------------------


    if (Name.text!.isEmpty && Username.text!.isEmpty && website.text!.isEmpty && aboutUser.text!.isEmpty && emailUser.text!.isEmpty && phoneUser.text!.isEmpty && genderUser.text!.isEmpty && (profileImageData == nil)) {
        print("error")

    }
}
else {
    print("image was nil")
}

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

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