webView:didFailLoadWithError -1004: 在 Phonegap ios 中连接 google plus 时无法连接到服务器

2024-04-06

在获取配置文件数据之前接受 google plus 身份验证时,我收到“webView:didFailLoadWithError -1004: 无法连接到服务器”错误。这些代码之前可以正常工作。现在我面临这些错误。不知道为什么我无法连接。请帮助我消除这些错误。下面是我在 ios 的 Phonegap (3.4.0) 中集成 google plus 的代码。

 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 文件中并包含在您的项目中。当你想访问谷歌登录API时点击按钮调用function callGoogle()其余的将由这段代码完成。不要忘记添加您的客户端 ID 和 Client_Secret 密钥。它对我来说工作得很好。您需要 inappbrowser cordova 插件。

      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
        }
      });
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

webView:didFailLoadWithError -1004: 在 Phonegap ios 中连接 google plus 时无法连接到服务器 的相关文章

  • JavaFX:在 WebView img 标签中未加载本地图像

    以下是我的代码 一切安好 我可以加载远程页面 我可以放置 HTML 内容 但我的img标签显示一个X标志表示无法加载图像 Note 我的图像与类位于同一个包中JavaFX在 Smiley 文件夹中 我可以列出所有图像 这意味着路径没有问题
  • NSData 不接受有效的 base64 编码字符串

    我正在 iOS 7 客户端实现 JSON Web Token 身份验证 效果很好 我的应用程序接收令牌 并可以使用它们对我的服务器进行经过身份验证的调用 现在 我希望我的客户端代码检查令牌的过期日期 以便它知道何时重新进行身份验证 检查 J
  • GM 发布 Xcode 6 编译

    我刚刚下载了 Xcode 6 的 GM 版本 但无法编译并出现以下错误 Command Applications Xcode app Contents Developer Toolchains XcodeDefault xctoolchai
  • 如何通过填充 NSDictionary 以 JSON 格式发送 UIImage

    我正在尝试使用 JSON 将数据发送到服务器 我可以使用我的对象和关键参数创建 NSDictionary 但我想发送我的图片 图片是UIImage NSDictionary mainJSON NSDictionary dictionaryW
  • 在 iOS 中擦除绘图

    我正在开发一个绘图应用程序 我有一个UIBezierPath 我用它在touchesMoved中绘制 并将其转换为CGPath 然后在tCGplayer上绘制 这是我的代码 void touchesMoved NSSet touches w
  • 如何使用 WKWebView 正确实施身份验证质询?

    我正在构建一个网络浏览器 但在网络方面我真的是新手 我想测试下面的代码示例 但我没有现实生活中的示例可以使用 void webView WKWebView webView didReceiveAuthenticationChallenge
  • iPad 2 检测

    由于我没有 iPad 2 因此我需要知道调用 UIDevice currentDevice model 时它返回什么 我以为它只返回 iPad 但看来我错了 有人可以告诉我吗 Thanks 检查是否有带摄像头的 iPad BOOL isIP
  • iOS:加载时的设备方向

    似乎当我的应用程序加载时 它不知道其当前方向 UIInterfaceOrientation orientation UIDevice currentDevice orientation if orientation UIDeviceOrie
  • TestFlight 提供反馈按钮

    我正在使用 iOS 8 的最新 testflight 版本 我将自己添加为内部测试人员 现在当我使用 testflight 打开应用程序时 我找不到反馈按钮 如果有人有任何线索 请告诉我 您在 Testflight 应用程序中提供反馈 打开
  • NSCalendar 返回明年第一周上周一的错误日期

    我使用下面的代码使用随机日期来计算上周一 哪个工作文件但我的代码在明年日期中断 下面是相同的代码 NSDate date NSDate dateWithTimeIntervalSince1970 1483620311 228 NSLog c
  • 如何检测 UISwipeGestureRecognizer 的结束?

    来自苹果文档 滑动是一种离散手势 因此每个手势仅发送一次关联的操作消息 void touchesEnded NSSet touches withEvent UIEvent event 当我使用 UISwipeGestureRecognize
  • Swift 3:如何访问48字节CFData中matrix_float3x3的值?

    我正在尝试访问内在矩阵answer https stackoverflow com a 48159895 9296667 通过运行下面的命令 我能够得到一个 48 字节的任意对象 https developer apple com docu
  • scntool:无法转换文件,失败原因:*** -[__NSSingleObjectArrayI objectAtIndex:]:索引 1 超出范围

    我正在 Xcode 9 3 下开发一个基于 iOS 11 3 SceneKit 的项目 我有几个 dae 文件格式的 3D 模型 每当我构建项目时 其中一个模型不会被复制到最终的 iOS 包中 深入研究错误 我在复制捆绑资源构建阶段收到以下
  • 如何使用云打印打印Android活动显示

    我正在尝试将 Google 云打印实现到应用程序中 遵循集成指南 https developers google com cloud print docs android 我试图通过打印 google com 来保持基本 单击我创建的打印按
  • mgwt - 以编程方式改变方向

    是否可以在 gwt mgwt 应用程序中更改强制执行特定的屏幕方向 可以说我希望用户始终以横向模式使用应用程序 这取决于 是作为phonegap应用程序 而不是在浏览器内部 如果您作为 Web 应用程序运行 则不需要t get any co
  • 如何在 Swift 中使用indexesOfObjectsPassingTest:

    IndexOfObjectsPassingTest 的声明在 Swift 中看起来像这样 func indexesOfObjectsPassingTest predicate AnyObject Int CMutablePointer
  • UIStackView分布均匀填充

    所以 我有一个UIStackView其中包含四 4 UIViews 如果我删除其中一 1 个UIViews 其他三 3 个将填满UIStackView 我的问题 如何添加最大高度UIView这样它就不会填满整个空间UIStackView即使
  • Admob 广告无法快速显示

    您好 我正在尝试将 admob 广告添加到已使用 swift 上传到应用商店的应用程序中 我在 admob 中制作了一个应用程序并复制了 appid 和广告 id 并显示了各自的横幅广告和插页式广告 这里的问题是当我写这行时 request
  • 无法从 iOS 中的框架访问 .nib(XIB) 文件

    我已经从现有的代码库中创建了一个框架 并尝试在新的代码库中使用它 这很好用 但是当我尝试访问属于我的框架包的一部分的 nib 文件时 我的应用程序崩溃了 这是我用来访问视图控制器 XIB 文件的代码 testViewController c
  • 使用 NSString 进行 UTF8 解码

    我是 Objective C 新手 尝试使用以下示例将格式错误的 UTF8 编码 NSString 转换为格式良好的字符串苹果文档 http developer apple com library mac documentation Coc

随机推荐