webView:didFailLoadWithError -1004:在Phonegap ios中连接google plus时无法连接到服务器 [英] webView:didFailLoadWithError -1004: Could not connect to the server while connecting google plus in Phonegap ios

查看:109
本文介绍了webView:didFailLoadWithError -1004:在Phonegap ios中连接google plus时无法连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在获取个人资料数据之前,我接受Google Plus身份验证时遇到"webView:didFailLoadWithError -1004:无法连接到服务器"错误.这些代码之前可以正常工作.现在我正面临这些错误.不知道为什么我无法连接.请帮助我摆脱这些错误.下面是我的代码,用于将google plus集成到iOS的Phonegap(3.4.0)中.

I am getting "webView:didFailLoadWithError -1004: Could not connect to the server" error while accepting google plus authentication before getting profile data. These code was working properly before. Now i am facing these error. No idea why i am not able to connect.Please help me to get rid of these error.Below is my code for integrating google plus in Phonegap (3.4.0) for ios.

 var googleapi = {
        //alert('ready');
        authorize: function(options) {
            var deferred = $.Deferred();

        //Build the OAuth consent page URL
        var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
            client_id: options.client_id,
            redirect_uri: options.redirect_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,
                    redirect_uri: options.redirect_uri,
                    grant_type: 'authorization_code'
                }).done(function(data) {
                    deferred.resolve(data);

                    $("#loginStatus").html('Name: ' + data.given_name);
                }).fail(function(response) {
                    deferred.reject(response.responseJSON);
                });
            } else if (error) {
                //The user denied access to the app
                deferred.reject({
                    error: error[1]
                });
            }
        });

        return deferred.promise();
    }
    };



    var accessToken;


    function callGoogle()

    {

    alert('starting');
    googleapi.authorize({
                        client_id: 'CLIENT_ID',
                        client_secret: 'CLIENT_SECRET',
                        redirect_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);

           }
           });

}

推荐答案

将此代码添加到一个js文件中,并包含在您的项目中.当您要访问按钮上的google login api时,单击呼叫function callGoogle()其余代码将由此代码完成.不要忘记添加客户端ID和Client_Secret密钥.它对我来说很好.您需要内置浏览器Cordova插件.

add this code in one js file and include in your project. when you want to access google login api on button click call function callGoogle() rest will be done by this code. Dont forget to add your client id and Client_Secret keys. Its working fine for me. You need inappbrowser cordova plugin.

      var googleapi = {
        authorize: function(options) {
            var deferred = $.Deferred();

            //Build the OAuth consent page URL
            var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
                client_id: options.client_id,
                redirect_uri: options.redirect_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 redirect_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 redirect_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,
                        redirect_uri: options.redirect_uri,
                        grant_type: 'authorization_code'
                    }).done(function(data) {
                        deferred.resolve(data);

                        $("#loginStatus").html('Name: ' + data.given_name);
                    }).fail(function(response) {
                        deferred.reject(response.responseJSON);
                    });
                } else if (error) {
                    //The user denied access to the app
                    deferred.reject({
                        error: error[1]
                    });
                }
            });

            return deferred.promise();
        }
    };
     var accessToken;
    var UserData=null;

    function callGoogle()
    {

    //  alert('starting');
        googleapi.authorize({
                            client_id: 'client_id',
                            client_secret: 'Client_Secret',
                            redirect_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
        }
      });
    }

这篇关于webView:didFailLoadWithError -1004:在Phonegap ios中连接google plus时无法连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆