Abdulmoiz Ahmer
Abdulmoiz Ahmer

Reputation: 2361

"The file “photo.jpg” couldn’t be opened because the text encoding of its contents can’t be determined." error in ios swift

I am new to ios. I used firebase google and facebook authentication, on signup i got photourl of current user. I used PINRemoteImage library to fetch the image and set it to imageview but while testing I am getting the following error.

Domain=NSCocoaErrorDomain Code=264 "The file “photo.jpg” couldn’t be opened because the text encoding of its contents can’t be determined." UserInfo={NSURL=https://lh6.googleusercontent.com/-VImwCn8xJng/AAAAAAAAAAI/AAAAAAAAAAc/Qlp17u7Qxzs/s96-c/photo.jpg}

Below is the code where image is being accessed:

let userInfo = network.getCurrentUserDate()
        setTextFields(userInfo: userInfo)


func setTextFields(userInfo:UserData){
        do{
            try profileImage.pin_setImage(from: URL(string: String(contentsOf: userInfo.getImageUrl()))!)
        }catch{
            print(error)
        }
    }

Here network is object of following class

class Networking{
    func getCurrentUserDate()->UserData{
        let currentUser = Auth.auth().currentUser
        return UserData(username: (currentUser?.displayName)!, email: 
        (currentUser?.email)!, url: (currentUser?.photoURL)!)
    }
}

//Here userinfo is object of following class 

class UserData{
    var userName:String
    var useremail:String
    var imageUrl:URL

    init(username:String,email:String,url:URL) {
        userName = username
        useremail = email
        imageUrl = url
    }

    func getuserName() -> String {
        return userName
    }

    func getEmail() -> String {
        return useremail
    }

    func getImageUrl() -> URL {
        return imageUrl
    }
}

Can anyone tell me what is wrong with my code

Upvotes: 1

Views: 766

Answers (1)

vadian
vadian

Reputation: 285210

First of all you don't need the get...() methods at all, get the values just with e.g. userInfo.imageUrl

class UserData {
    var userName: String
    var useremail: String
    var imageUrl: URL

    init(username: String, email: String, url: URL) {
        userName = username
        useremail = email
        imageUrl = url
    }
}

If you declare UserData as struct you don't even need the initializer

struct UserData {
    var userName, useremail: String
    var imageUrl: URL
} 

And if the three properties/members won't change declare them as constant

struct UserData {
    let userName, useremail: String
    let imageUrl: URL
} 

The error occurs because there is no String at the given URL, the image is saved as raw Data

Use imageUrl directly, change setTextFields to

func setTextFields(userInfo: UserData) {
    do {
        try profileImage.pin_setImage(from: userInfo.imageUrl)
    } catch {
        print(error)
    }
}

Upvotes: 2

Related Questions