0

I am building a social app with an avatar like instagram and using Amazon S3 for storage. For some reason the app compiles fine but when I scroll on the search page after uploading an avatar the app crashes and I get this error.

Thread 1 - fatal error - unexpectedly found nil while unwrapping an Optional value

This is the line of code where the error shows up...

private func avatarURL(for username: String) -> URL {
    return "https://s3.amazonaws.com/rest-of-link/\(username.lowercased())-avatar.jpg".URL!
}

I can scroll on the feed page with avatars showing just fine. Also, when I change the link to a black web page there are no avatars but I can scroll just fine without getting this error. Any idea what this could be?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Obviously the `!` is causing your crash because the result of `URL` is `nil`. And of course this means the string isn't a valid URL. – rmaddy Jun 09 '18 at 17:43

1 Answers1

0

Looks like the ! mark (force unwrap) crashes your app. try this:

private func avatarURL(for username: String) -> URL? {
    return "https://s3.amazonaws.com/rest-of-link/\(username.lowercased().addingPercentEncoding(withAllowedCharacters: .urlPathAllowed))-avatar.jpg".URL
}

Make sure to safely unwrap avatarURL(for username: "someUsername"). You can do something like this:

if let url = avatarURL(for username: "someUsername") {
     // set imageView.image here because URL is valid
} else {
    //maybe set imageView.image = nil
}

EDIT: try this:

private func avatarURL(for username: String) -> URL? {
   let lowercase = username.lowercased()
   return URL(string: "https://s3.amazonaws.com/rest-of-link/\(lowercase)-avatar.jpg")
}
Michael Voline
  • 383
  • 3
  • 13
  • Hi, thanks for your response. The first part worked in the sense that it doesn't crash but the avatar images don't show up. Not sure how to implement the second part. Sorry I'm very new to Swift. – tommycellcal Jun 10 '18 at 00:15