Facebook Auth에서 이메일정보를 반환하지 않을 때
Problem
//페이스북에서 이름과 이메일 정보를 얻어낸다.
override fun requestFacebookProfile(loginResult: LoginResult) {
val request = GraphRequest.newMeRequest(loginResult.accessToken) { obj, response ->
try {
val email = obj.getString("email").toString()
requestToken(loginResult, email)
} catch (e: Exception) {
Log.d("SSS", "requestFacebookProfile(): $e" )
view.showToast(R.string.intro_network)
}
}
val parameters = Bundle()
parameters.putString("fields", "name, email")
request.parameters = parameters
request.executeAsync()
}
org.json.JSONException: No value for email
catch (e: Exception) 에 걸려서 위의 에러메시지가 나옴
Solution
val email = obj.optString("email").toString()
getString 대신 optString
값이 없는경우, 에러대신 공백("")을 반환해준다.
에러는 안나지만 이메일은 공백이다.
The difference is that optString
returns the empty string (""
) if the key you specify doesn't exist.
getString
on the other hand throws a JSONException
.
Use getString
if it's an error for the data to be missing, or optString
if you're not sure if it will be there.
참고: https://stackoverflow.com/questions/34846823/org-json-jsonexception-no-value-for
이메일을 반환해주지 않는 이유?
페이스북은 전화번호 만으로도 가입할 수 있어서 이메일정보가 없는 유저가 있다.
실험해보니 이메일 없이도 가입 가능.
//페이스북에서 이름과 이메일 정보를 얻어낸다.
override fun requestFacebookProfile(loginResult: LoginResult) {
val request = GraphRequest.newMeRequest(loginResult.accessToken) { obj, response ->
try {
var email = obj.optString("email")
val facebookId = obj.optString("id")
//이메일이 없으면 페이스북 아이디로 대체
if(email.isEmpty()) email = facebookId + "@facebook.com"
requestToken(loginResult, email)
} catch (e: Exception) { }
}
val parameters = Bundle()
parameters.putString("fields", "name, email")
request.parameters = parameters
request.executeAsync()
}
페이스북아이디에 "@facebook.com"을 붙여서 이메일 텍스트 생성.