Search code examples
iosswiftswift3swift4

Function that downloads photos from the internet not working


I have this code:

struct MyPackageData: Codable {
    let versionDate: String
    let photosSizes, packshotsSizes, inspirationsPhotoSizes, conceptsSlidesSizes: [String: Int]
    let tipsSlidesSizes, leafletsSlidesSizes, leafletsPdfSlidesSizes: [String: Int]
}
func downloadImagesTipsSlides(toDownloads: MyPackageData, savedURL: String){
        do {
            let dateToParse = toDownloads.tipsSlidesSizes
            for photo in dateToParse {
                let fileNamePhoto = photo.key
                let checkLocalCopyFileIsAvailable = checkLocalFileCopyIsAvailable(fileName: (AppGlobalManager.sharedManager.loggedUser?.selectedLanguage)! + "/" + FileFolders.GET_TIPS_SLIDES.rawValue + "/" + "\(fileNamePhoto)")
                if checkLocalCopyFileIsAvailable == false {
                    let productImageUrl : URL = URL(string:  "\(ApiConstans.fullPath)?action=\(FileFolders.GET_TIPS_SLIDES.rawValue)&name=\(fileNamePhoto)&resolution=FHD&lang=" + (AppGlobalManager.sharedManager.loggedUser?.getUserLanguageUrl())!)!
                    remoteResource(at: productImageUrl, fileSize: photo.value) { (isImage) in
                        if isImage == false {
                        }
                        if isImage == true {
                            self.saveDownloadImages(fileInternetUrl: productImageUrl, fileName: "\(fileNamePhoto)", savedURL: savedURL)
                        }
                    }
                } else {
                    print("I have photo \(fileNamePhoto) - nie robię nic")
                }
            }
        }
    }


func remoteResource(at url: URL, fileSize: Int, isImage: @escaping ((Bool) -> Void)) {
    let request = URLRequest(url: url)
    debugPrint(request)
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let data = data, let image = UIImage(data: data) {
            if let _ = UIImageJPEGRepresentation(image, 1.0) {
                isImage(true)
            } else if let _ = UIImagePNGRepresentation(image) {
                isImage(true)
            } else {
                isImage(false)
            }

        } else {
            isImage(false)
        }
        isImage(true) // remove
    }
    task.resume()
}


func saveDownloadImages(fileInternetUrl: URL, fileName: String, savedURL: String){
        let documentsDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
        let fullImagesPath = documentsDir.appendingPathComponent(savedURL)
        let cms = ServerConnect()
        print("XX \(fullImagesPath)")
        cms.downloadedFileFromInternet(fileInternetUrl: fileInternetUrl, saveToPath: fullImagesPath, fileName: fileName,  completion: { (data) in
            switch data {
            case .succes:
                print("")
            case .error(let error):
                //self.errorLoginMessage(txt: "MainView - Error 110: Problem with download images. \(error)", title: "Blad".localized())
                print("")
                break
            }
        })
    }

When I error: Thread 7: Fatal error: Unexpectedly found nil while unwrapping an Optional value

in line:

let productImageUrl : URL = URL(string:  "\(ApiConstans.fullPath)?action=\(FileFolders.GET_TIPS_SLIDES.rawValue)&name=\(fileNamePhoto)&resolution=FHD&lang=" + (AppGlobalManager.sharedManager.loggedUser?.getUserLanguageUrl())!)!

My debug console:

debug
(source: home.pl)

I have problem with file with name: - wolność ogłoszenia.jpg - Wydajność wagowa___004.jpg

etc.

With filename with normal name: 1.jpg, 139485.jpg, 14383.jpg - this code works correctly.

The above code is to download photos from the internet and save them to the device's memory. Files with no special names work correctly.

I can not change the file name on the server.

Does anyone know how to fix it?


Solution

  • Don't force unwrap things you will save so many common crashes.

    let productImageUrl : URL = URL(string:  "\(ApiConstans.fullPath)?action=\(FileFolders.GET_TIPS_SLIDES.rawValue)&name=\(fileNamePhoto)&resolution=FHD&lang=" + (AppGlobalManager.sharedManager.loggedUser?.getUserLanguageUrl())!)!
    

    This String is not a URL. Unwrap using guard let/ if let :

    guard let languageUrl = AppGlobalManager.sharedManager.loggedUser?.getUserLanguageUrl(), let urlString = "\(ApiConstans.fullPath)?action=\(FileFolders.GET_TIPS_SLIDES.rawValue)&name=\(fileNamePhoto)&resolution=FHD&lang=\(languageUrl)".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let productImageUrl = URL(string:  urlString) else {
        print("Problem in converting string to URL")
        return
    }
    print(productImageUrl)
    

    In simple words your String should have "http://" or "https://" in the beginning to convert that String to URL. For something in document directory you add "file://".