webView: didFailLoadWithError -1004: no se pudo conectar al server mientras se conectaba google plus en Phonegap ios

Obtengo el error "webView: didFailLoadWithError -1004: no se pudo conectar al server" mientras aceptaba la authentication de google plus antes de get los datos del perfil. Estos códigos funcionaban correctamente antes. Ahora me enfrento a este error. No tengo idea de por qué no puedo conectarme. Por favor, ayúdame a deshacerte de estos errores. A continuación, se encuentra mi código para integrar google plus en Phonegap (3.4.0) para iOS.

var googleapi = { //alert('ready'); authorize: function(options) { var defernetworking = $.Defernetworking(); //Build the OAuth consent page URL var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({ client_id: options.client_id, networkingirect_uri: options.networkingirect_uri, response_type: 'code', scope: options.scope }); //Open the OAuth consent page in the InAppBrowser var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=yes'); $(authWindow).on(' ', function(e) { var url = e.originalEvent.url; var code = /\?code=(.+)$/.exec(url); var error = /\?error=(.+)$/.exec(url); if (code || error) { //Always close the browser when match is found authWindow.close(); } if (code) { //Exchange the authorization code for an access token $.post('https://accounts.google.com/o/oauth2/token', { code: code[1], client_id: options.client_id, client_secret: options.client_secret, networkingirect_uri: options.networkingirect_uri, grant_type: 'authorization_code' }).done(function(data) { defernetworking.resolve(data); $("#loginStatus").html('Name: ' + data.given_name); }).fail(function(response) { defernetworking.reject(response.responseJSON); }); } else if (error) { //The user denied access to the app defernetworking.reject({ error: error[1] }); } }); return defernetworking.promise(); } }; var accessToken; function callGoogle() { alert('starting'); googleapi.authorize({ client_id: 'CLIENT_ID', client_secret: 'CLIENT_SECRET', networkingirect_uri: 'http://localhost', scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' }).done(function(data) { accessToken=data.access_token; alert(accessToken); // $loginStatus.html('Access Token: ' + data.access_token); console.log(data.access_token); getDataProfile(); }); } function getDataProfile() { var term=null; //accessToken=null; //alert("getting user data="+accessToken); $.ajax({ url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken, type:'GET', data:term, dataType:'json', error:function(jqXHR,text_status,strError){ }, success:function(data) { var item; var dat=data.properties; alert("first name="+data.given_name+" last name="+data.family_name+" gender="+data.gender+" email="+data.email); console.log(data); } }); } 

agregue este código en un file js e incluya en su proyecto. cuando desee acceder a google login api en el button click la function callGoogle() llamada function callGoogle() rest se realizará mediante este código. No te olvides de agregar tu ID de cliente y las keys Client_Secret. Está funcionando bien para mí. Necesita el complemento cordova inappbrowser.

  var googleapi = { authorize: function(options) { var defernetworking = $.Defernetworking(); //Build the OAuth consent page URL var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({ client_id: options.client_id, networkingirect_uri: options.networkingirect_uri, response_type: 'code', scope: options.scope }); //Open the OAuth consent page in the InAppBrowser var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no'); //The recommendation is to use the networkingirect_uri "urn:ietf:wg:oauth:2.0:oob" //which sets the authorization code in the browser's title. However, we can't //access the title of the InAppBrowser. // //Instead, we pass a bogus networkingirect_uri of "http://localhost", which means the //authorization code will get set in the url. We can access the url in the //loadstart and loadstop events. So if we bind the loadstart event, we can //find the authorization code and close the InAppBrowser after the user //has granted us access to their data. $(authWindow).on('loadstart', function(e) { var url = e.originalEvent.url; var code = /\?code=(.+)$/.exec(url); var error = /\?error=(.+)$/.exec(url); if (code || error) { //Always close the browser when match is found authWindow.close(); } if (code) { //Exchange the authorization code for an access token $.post('https://accounts.google.com/o/oauth2/token', { code: code[1], client_id: options.client_id, client_secret: options.client_secret, networkingirect_uri: options.networkingirect_uri, grant_type: 'authorization_code' }).done(function(data) { defernetworking.resolve(data); $("#loginStatus").html('Name: ' + data.given_name); }).fail(function(response) { defernetworking.reject(response.responseJSON); }); } else if (error) { //The user denied access to the app defernetworking.reject({ error: error[1] }); } }); return defernetworking.promise(); } }; var accessToken; var UserData=null; function callGoogle() { // alert('starting'); googleapi.authorize({ client_id: 'client_id', client_secret: 'Client_Secret', networkingirect_uri: 'http://localhost', scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' }).done(function(data) { accessToken=data.access_token; // alert(accessToken); // $loginStatus.html('Access Token: ' + data.access_token); console.log(data.access_token); console.log(JSON.stringify(data)); getDataProfile(); }); } // This function gets data of user. function getDataProfile() { var term=null; // alert("getting user data="+accessToken); $.ajax({ url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken, type:'GET', data:term, dataType:'json', error:function(jqXHR,text_status,strError){ }, success:function(data) { var item; console.log(JSON.stringify(data)); // Save the userprofile data in your localStorage. localStorage.gmailLogin="true"; localStorage.gmailID=data.id; localStorage.gmailEmail=data.email; localStorage.gmailFirstName=data.given_name; localStorage.gmailLastName=data.family_name; localStorage.gmailProfilePicture=data.picture; localStorage.gmailGender=data.gender; } }); disconnectUser(); } function disconnectUser() { var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accessToken; // Perform an asynchronous GET request. $.ajax({ type: 'GET', url: revokeUrl, async: false, contentType: "application/json", dataType: 'jsonp', success: function(nullResponse) { // Do something now that user is disconnected // The response is always undefined. accessToken=null; console.log(JSON.stringify(nullResponse)); console.log("-----signed out..!!----"+accessToken); }, error: function(e) { // Handle the error // console.log(e); // You could point users to manually disconnect if unsuccessful // https://plus.google.com/apps } }); } 

Puede get datos de token de acceso y perfil de usuario usando el código siguiente. Simplemente conecte su evento de button a la function "onGooglePlusLogin" y reemplace client_id y screte_id.

He probado en iPhone y dispositivos Android con el proyecto phonegap 3.4.0.

¡Aclamaciones!

 var GoogleLogin = function (id, secret) { var clientId = id; var clientSecret = secret; var accessToken = {}; var authWindow = null; var endSignin = {}; var openAuthWindow = function () { var urlAuth = "https://accounts.google.com/o/oauth2/auth?" + "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&" + "networkingirect_uri=http://localhost&" + "response_type=code&" + "client_id=" + clientId; // Open InAppBrowser to get authorization code authWindow = window.open(urlAuth, '_blank', 'location=yes,closebuttoncaption=Done'); authWindow.addEventListener('loadstart', parseRedirectUrl); }; var parseRedirectUrl = function (e) { var url = e.url; var thereIsCode = url.indexOf("code="); var thereIsError = url.indexOf("error="); if (thereIsCode != -1) { authWindow.close(); var toMatch = "code=([^&#]*)"; var regex = new RegExp(toMatch); var result = regex.exec(url); if (result != null) { var code = result[1]; exchangeCodeForTokens(code); } } else if (thereIsError != -1) { authWindow.close(); localStorage["accessToken"] = null; endSignin(-1); } }; var exchangeCodeForTokens = function (code) { var dataQuery = "code=" + code + "&" + "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "networkingirect_uri=http://localhost&" + "grant_type=authorization_code"; requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackTokens); }; var callBackTokens = function (resp) { var tokensResp = eval('(' + resp + ')'); if (tokensResp.access_token) { localStorage["accessToken"] = tokensResp.access_token; localStorage["refreshToken"] = tokensResp.refresh_token; localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in; accessToken = tokensResp.access_token; endSignin(accessToken); } else { accessToken = null; localStorage["accessToken"] = null; endSignin(-1); } }; var getAccessToken = function (refreshToken) { var dataQuery = "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "refresh_token=" + refreshToken + "&" + "grant_type=refresh_token"; requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackRefreshToken); }; var callBackRefreshToken = function (resp) { var tokensResp = eval('(' + resp + ')'); if (tokensResp.access_token) { localStorage["accessToken"] = tokensResp.access_token; localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in; accessToken = tokensResp.access_token; endSignin(accessToken); } else { accessToken = null; localStorage["accessToken"] = null; endSignin(-1); } }; var requestTokens = function (url, data, callback) { var xmlreq = new XMLHttpRequest(); xmlreq.onreadystatechange = function () { if (xmlreq.readyState == 4) { callback(xmlreq.responseText); } }; xmlreq.open("POST", url, true); xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlreq.send(data); }; var isLoggedIn = function (callback) { endSignin = callback; accessToken = localStorage["accessToken"]; if (accessToken == "null") { accessToken = null; } if (accessToken !== null && typeof (accessToken) !== 'undefined') { var refreshTime = localStorage["refreshTime"]; var refreshToken = localStorage["refreshToken"]; var currentTime = (new Date()).getTime(); if (currentTime < refreshTime) { endSignin(accessToken); } else { getAccessToken(refreshToken); } } else { endSignin(-1); } }; var startSignin = function (callbackEnd) { endSignin = callbackEnd; openAuthWindow(); }; var logOut = function () { accessToken = null; localStorage["accessToken"] = null; localStorage["refreshToken"] = null; }; return { startSignin: startSignin, isLoggedIn: isLoggedIn, logOut: logOut }; }; function onGooglePlusLogin() { var clientId = "YOUR_CLIENT_ID"; var clientSecret = "SECRET_ID"; // Create login object and initialize it with your app client id and secret var gl = new GoogleLogin(clientId, clientSecret); gl.startSignin(endLogin); } function endLogin(result) { if (result === -1) { // Login was not successful :( alert('Google Login failed!'); } else { // If successful login, use access_token to get profile name getProfileData(result); } } function getProfileData(result) { if (result !== null && typeof (result) !== 'undefined') { var urlAPI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + result; var xmlreq = new XMLHttpRequest(); xmlreq.onreadystatechange = function () { if (xmlreq.readyState == 4 && xmlreq.status == 200) { var response = eval('(' + xmlreq.responseText + ')'); if (response && response.email && response.id) { // Profile data alert(JSON.stringify(response)); } else { alert("Google Login failed!"); } } }; xmlreq.open("GET", urlAPI, true); xmlreq.send(); } }