Fetch Google profile image url by UID

410 views Asked by At

I want to fetch the google profile image when UID is given to me . I have this reference but m getting how to hit this url . Please anyone provide me some example.

EDIT: Here is my code

var googleImageUrl: URL?{
    let urlString = "https://www.googleapis.com/plus/v1/people/\(uid)?fields=image&key=AIzaSyBfjHpl8DjU0IGw9mXbvK6HoNpY"
    return URL(string: urlString)
}

Alamofire.request(url)
    .validate()
    .responseJSON(completionHandler: { (response) in
        if response.result.isSuccess {
            let json = response.result.value as? [String: Any]


        } else {
            let apiError = ApiError(response: response)

        }
    })

when hitting this api, am always getting the error. Why i am not getting the response ?

2

There are 2 answers

2
Rashwan L On BEST ANSWER

You have two options:

Using Googles API, requires API key:

https://www.googleapis.com/plus/v1/people/{UID}?fields=image&key={YOUR_API_KEY}

Using Googles Picasaweb which does not require any API key:

http://picasaweb.google.com/data/entry/api/user/{UID}?alt=json

Code to get the image:

// Check what you want to return in the onCompletion and use it
func getImage(uid: String, onCompletion: @escaping (String) -> Void, onError: @escaping (NSError) -> Void) {
    let url = "https://www.googleapis.com/plus/v1/people/\(uid)?fields=image&key=AIzaSyBfjHpl8DjU0IGw9mXbvK6HoNpY"

    let headers = [
        "Content-Type": "application/json"
    ]

    Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
        .responseJSON { response in
            if let object = response.result.value as? [String:Any] {
                print(object)
                // use the onCompletion in here
            }
    }
}
0
Amos Yuen On

The reference you listed points to the Google People API, which is different than the Google+ People API. If you want to use the Google People API you should use https://people.googleapis.com/v1/people/{UID}?personFields=photo&key={YOUR_API_KEY}

There are official examples at: https://developers.google.com/people/v1/read-people#get-the-person-for-a-google-account