GVKun编程网logo

默认浏览器中的OSX Swift打开URL(贴吧热门评论)

21

这篇文章主要围绕默认浏览器中的OSXSwift打开URL和贴吧热门评论展开,旨在为您提供一份详细的参考资料。我们将全面介绍默认浏览器中的OSXSwift打开URL的优缺点,解答贴吧热门评论的相关问题,

这篇文章主要围绕默认浏览器中的OSX Swift打开URL贴吧热门评论展开,旨在为您提供一份详细的参考资料。我们将全面介绍默认浏览器中的OSX Swift打开URL的优缺点,解答贴吧热门评论的相关问题,同时也会为您带来android – 在WebView中打开URL而不是默认浏览器、c# – 如何在WinForm的浏览器中打开默认Windows浏览器并将HTTP发布数据发送到打开的URL?、C#如何在默认浏览器中打开、delphi – 在默认浏览器中打开网页,在url中使用双引号(“)的实用方法。

本文目录一览:

默认浏览器中的OSX Swift打开URL(贴吧热门评论)

默认浏览器中的OSX Swift打开URL(贴吧热门评论)

如何通过使用Swift作为编程语言并使用OSX作为平台在系统默认浏览器中打开url。

我在UIApplication中发现了很多东西,例如

UIApplication.sharedApplication().openURL(NSURL(string: object.url))

但这仅适用于iOS而不适用于OSX

与发射服务,我发现有迅速没有例子并没有过时的OSX
10.10很多

欢迎任何帮助-谢谢。

答案1

小编典典

Swift 3或更高版本

import Cocoalet url = URL(string: "https://www.google.com")!if NSWorkspace.shared.open(url) {    print("default browser was successfully opened")}

android – 在WebView中打开URL而不是默认浏览器

android – 在WebView中打开URL而不是默认浏览器

我正在创建简单的Webview应用程序与文本视图上的一些链接,并打开webview而不是默认浏览器中的链接.我的文字视图包含各种不同的URLS,我正在尝试打开我的应用程序的webview中的每个链接.

这里代码:

tv.setText("www.google.com  www.facebook.com  www.yahoo.com");
tv.setMovementMethod(LinkMovementMethod.getInstance());;
tv.setText(Html.fromHtml(tv.getText().toString()));
Linkify.addLinks(tv,Linkify.WEB_URLS);


WebViewClient yourWebClient = new WebViewClient()
       {
           // Override page so it's load on my view only
           @Override
           public boolean shouldOverrideUrlLoading(WebView  view,String  url)
           {
            // This line we let me load only pages inside Firstdroid Webpage
            if ( url.contains("www") == true )
               // Load new URL Don't override URL Link
               return false;

            // Return true to override url loading (In this case do nothing).
            return true;
           }
       };

wv.getSettings().setJavaScriptEnabled(true);   
    wv.getSettings().setSupportZoom(true);      

    wv.getSettings().setBuiltInZoomControls(true); 
    wv.setWebViewClient(yourWebClient);

    // Load URL
    wv.loadUrl(url);

已经尝试了this,this和this的例子,但是无法解决我在textview中的多个链接的问题.请帮我解决这个问题.谢谢你的帮助.

编辑
我的Textview包含字符串:

hello xyz some more statements... xyz.com/abc/
hello xyz some more statements... xyz.com/abc/
hello xyz some more statements... xyz.com/abc/
hello xyz some more statements... xyz.com/abc/

像这样它有很多字符串和多个URL

解决方法

以下问题需要解决:

>链接TextView
>找到一种方式来收听TextView中的链接
>获取点击的链接的URL,并将其加载到WebView中
>可选:使TextView可点击,而不会失去选择文本的能力
>可选:在TextView中处理格式化的文本(不同的文字大小和样式)

#1链接TextView

这是最简单的问题,你已经解决了这个问题.我建议这样做:

String text = "These are some sample links:\nwww.google.com\nwww.facebook.com\nwww.yahoo.com";
Spannable spannable = new SpannableString( Html.fromHtml(text) );
Linkify.addLinks(spannable,Linkify.WEB_URLS);

我在这里使用一个Spannable来解决问题#2.

#2#3收听链接的点击并在WebView中打开它们

要查看链接何时被点击并检索我们必须打开的URL,我们用LinkSpan替换TextView中的所有URLSpans(这就是为什么我们需要一个Spannable):

URLSpan[] spans = spannable.getSpans(0,spannable.length(),URLSpan.class);
for (URLSpan urlSpan : spans) {
    LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
    int spanStart = spannable.getSpanStart(urlSpan);
    int spanEnd = spannable.getSpanEnd(urlSpan);
    spannable.setSpan(linkSpan,spanStart,spanEnd,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.removeSpan(urlSpan);
}

我们的LinkSpan只是抓住点击的网址,并在WebView中打开它:

private class LinkSpan extends URLSpan {
    private LinkSpan(String url) {
        super(url);
    }

    @Override
    public void onClick(View view) {
        String url = getURL();
        if (mWebView != null && url != null) {
            mWebView.loadUrl(url);
        }
    }
}

现在显然,我们必须在实例变量中保留对WebView的引用,以使其工作.为了使这个答案尽可能的短,我选择将LinkSpan定义为内部类,但我建议将其定义为顶级.注册一个监听器,或者将WebView作为参数传递给构造函数.

没有将MovementMethod设置为LinkMovementMethod,TextView将不会打开链接:

tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(spannable,BufferType.SPANNABLE);

最后但并非最不重要的是我们确保WebView不启动浏览器,而是加载该应用程序中的页面:

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view,String url) {
        // we handle the url ourselves if it's a network url (http / https) 
        return ! URLUtil.isNetworkUrl(url);
    }
});

#4可点击并选择TextView#5格式的文本

如果MovementMethod设置为LinkMovementMethod,您可以单击链接,但是您不能再选择文本(您需要使用ArrowKeyMovementMethod).为了解决这个问题,我创建了一个自定义的MoveMethod类,它继承自ArrowKeyMovementMethod,并添加了点击链接的功能.最重要的是可以处理格式化的文本.因此,如果您决定在TextView中使用不同的字体大小和样式,则以下MovementMethod将被覆盖(与EditTexts一起使用):

/**
 * ArrowKeyMovementMethod does support selection of text but not the clicking of links.
 * LinkMovementMethod does support clicking of links but not the selection of text.
 * This class adds the link clicking to the ArrowKeyMovementMethod.
 * We basically take the LinkMovementMethod onTouchEvent code and remove the line
 *      Selection.removeSelection(buffer);
 * which deselects all text when no link was found.
 */
public class EnhancedLinkMovementMethod extends ArrowKeyMovementMethod {

    private static EnhancedLinkMovementMethod sInstance;

    private static Rect sLineBounds = new Rect();

    public static MovementMethod getInstance() {
        if (sInstance == null) {
            sInstance = new EnhancedLinkMovementMethod();
        }
        return sInstance;
    }

    @Override
    public boolean onTouchEvent(TextView widget,Spannable buffer,MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {

            int index = getCharIndexAt(widget,event);
            if (index != -1) {
                ClickableSpan[] link = buffer.getSpans(index,index,ClickableSpan.class);
                if (link.length != 0) {
                    if (action == MotionEvent.ACTION_UP) {
                        link[0].onClick(widget);
                    }
                    else if (action == MotionEvent.ACTION_DOWN) {
                        Selection.setSelection(buffer,buffer.getSpanStart(link[0]),buffer.getSpanEnd(link[0]));
                    }
                    return true;
                }
            }
            /*else {
                Selection.removeSelection(buffer);
            }*/

        }

        return super.onTouchEvent(widget,buffer,event);
    }

    private int getCharIndexAt(TextView textView,MotionEvent event) {
        // get coordinates
        int x = (int) event.getX();
        int y = (int) event.getY();
        x -= textView.getTotalPaddingLeft();
        y -= textView.getTotalPaddingTop();
        x += textView.getScrollX();
        y += textView.getScrollY();

        /*
         * fail-fast check of the line bound.
         * If we're not within the line bound no character was touched
         */
        Layout layout = textView.getLayout();
        int line = layout.getLineForVertical(y);
        synchronized (sLineBounds) {
            layout.getLineBounds(line,sLineBounds);
            if (! sLineBounds.contains(x,y)) {
                return -1;
            }
        }

        // retrieve line text
        Spanned text = (Spanned) textView.getText();
        int linestart = layout.getLinestart(line);
        int lineEnd = layout.getLineEnd(line);
        int lineLength = lineEnd - linestart;
        if (lineLength == 0) {
            return -1;
        }
        Spanned lineText = (Spanned) text.subSequence(linestart,lineEnd);

        // compute leading margin and subtract it from the x coordinate
        int margin = 0;
        LeadingMarginSpan[] marginSpans = lineText.getSpans(0,lineLength,LeadingMarginSpan.class);
        if (marginSpans != null) {
            for (LeadingMarginSpan span : marginSpans) {
                margin += span.getLeadingMargin(true);
            }
        }
        x -= margin;

        // retrieve text widths
        float[] widths = new float[lineLength];
        TextPaint paint = textView.getPaint();
        paint.getTextWidths(lineText,widths);

        // scale text widths by relative font size (absolute size / default size)
        final float defaultSize = textView.getTextSize();
        float scaleFactor = 1f;
        AbsoluteSizeSpan[] absspans = lineText.getSpans(0,AbsoluteSizeSpan.class);
        if (absspans != null) {
            for (AbsoluteSizeSpan span : absspans) {
                int spanStart = lineText.getSpanStart(span);
                int spanEnd = lineText.getSpanEnd(span);
                scaleFactor = span.getSize() / defaultSize;
                int start = Math.max(linestart,spanStart);
                int end = Math.min(lineEnd,spanEnd);
                for (int i = start; i < end; i++) {
                    widths[i] *= scaleFactor;
                }
            }
        }

        // find index of touched character
        float startChar = 0;
        float endChar = 0;
        for (int i = 0; i < lineLength; i++) {
            startChar = endChar;
            endChar += widths[i];
            if (endChar >= x) {
                // which "end" is closer to x,the start or the end of the character?
                int index = linestart + (x - startChar < endChar - x ? i : i + 1);
                //Logger.e(Logger.LOG_TAG,"Found character: " + (text.length()>index ? text.charat(index) : ""));
                return index;
            }
        }

        return -1;
    }
}

完成活动代码

以下是我使用的完整示例活动代码.它应该完全符合你想要的它使用我的EnhandedMovementMethod,但您可以使用一个简单的LinkMovementMethod(具有前面提到的缺点).

public class LinkTestActivity extends Activity {

    private WebView mWebView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webView);
        TextView tv = (TextView) findViewById(R.id.textView);

        String text = "These are some sample links:\nwww.google.com\nwww.facebook.com\nwww.yahoo.com";

        // Linkify the TextView
        Spannable spannable = new SpannableString( Html.fromHtml(text) );
        Linkify.addLinks(spannable,Linkify.WEB_URLS);

        // Replace each URLSpan by a LinkSpan
        URLSpan[] spans = spannable.getSpans(0,URLSpan.class);
        for (URLSpan urlSpan : spans) {
            LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
            int spanStart = spannable.getSpanStart(urlSpan);
            int spanEnd = spannable.getSpanEnd(urlSpan);
            spannable.setSpan(linkSpan,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannable.removeSpan(urlSpan);
        }

        // Make sure the TextView supports clicking on Links
        tv.setMovementMethod(EnhancedLinkMovementMethod.getInstance());
        tv.setText(spannable,BufferType.SPANNABLE);

        // Make sure we handle clicked links ourselves
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                // we handle the url ourselves if it's a network url (http / https) 
                return ! URLUtil.isNetworkUrl(url);
            }
        });

        mWebView.getSettings().setJavaScriptEnabled(true);   
        mWebView.getSettings().setSupportZoom(true);      
        mWebView.getSettings().setBuiltInZoomControls(true);
    }

    private class LinkSpan extends URLSpan {
        private LinkSpan(String url) {
            super(url);
        }

        @Override
        public void onClick(View view) {
            String url = getURL();
            if (mWebView != null && url != null) {
                mWebView.loadUrl(url);
            }
        }
    }
}

c# – 如何在WinForm的浏览器中打开默认Windows浏览器并将HTTP发布数据发送到打开的URL?

c# – 如何在WinForm的浏览器中打开默认Windows浏览器并将HTTP发布数据发送到打开的URL?

我想在WinForm应用程序的默认浏览器中使用我的应用程序打开URL.
然后发送一些数据作为HTTP POST方法而不是查询字符串.
现在的问题是,如果我想在我使用的默认浏览器中打开URL
这段代码:

Process.Start("http://www.ketabchin.com/sort)

但在此命令中,我无法将发布数据发送到该URL
然后我用这个代码:

Public Shared Function PostMessagetoURL(url As String) As String
    Dim request As WebRequest = WebRequest.Create("https://www.ketabchin.com/windows-logged")
    request.Method = "POST"
    Dim postData As String = "u=" & FrmMain.Username & "&p=" & FrmMain.Password & "&url=" & url
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    Dim dataStream As Stream = request.GetRequestStream()
    dataStream.Write(byteArray,byteArray.Length)
    dataStream.Close()
    Dim response As WebResponse = request.GetResponse()
    Console.WriteLine(CType(response,HttpWebResponse).StatusDescription)
    dataStream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()

    reader.Close()
    dataStream.Close()
    response.Close()
    Return responseFromServer
End Function

这个将HTTP POST请求数据发送到url但我无法在默认Web浏览器中打开它或响应.
我怎样才能做到这一点?
这个行动背后的逻辑是.我有一个WinForm应用程序,当我的用户点击我的应用程序中的“转到网站”按钮.我想打开浏览器并将登录数据发送到登录页面,这样用户就可以在日志记录模式下访问该站点.

解决方法

我不知道您的问题是否仍然需要解决方案,但我使用您的代码来替代类似的问题.我有相同的请求,我需要用户点击AppForm按钮登录网站,但我没有找到任何方法将发布数据从VB应用程序发送到导航器(可能是一个解决方案可能存在与IE /边缘,但我的用户可以使用IE / FF / Chrome).以下是我为寻找解决方案所采取的步骤:

>用户必须单击以连接的按钮正在使用您的代码
> postData包含网站识别用户所需的所有数据(如用户名和密码)IP地址
>网站检查这些数据,如果一切正常,它会生成一个唯一的32位密钥并将其存储在数据库中
>然后网站发送json响应{“status”=> “ok”,“token”=> $key,“ip”=> $ipFromPostRequest}
> VB应用程序现在正在打开一个程序(您可以找到一些代码来打开默认浏览器的链接,如果没有定义IE或FF),其链接如http://www.website.com/auto-login/32-BITS-GENERATED-KEY
>如果密钥和IP对应,网站将检查数据库
> Web站点创建会话并将用户重定向到home并从数据库中删除Key

我认为这不是出于安全原因的最佳解决方案,但就我而言,这是一个具有独特计算机名称和内部IP地址的compagny网络,此过程正在运行.

C#如何在默认浏览器中打开

C#如何在默认浏览器中打开

我正在设计一个小型 C# 应用程序,其中有一个 Web
浏览器。我目前在我的计算机上拥有所有默认设置,说谷歌浏览器是我的默认浏览器,但是当我单击应用程序中的链接以在新窗口中打开时,它会打开 Internet
Explorer。有没有办法让这些链接在默认浏览器中打开?还是我的电脑有问题?

我的问题是我的应用程序中有一个网络浏览器,所以假设你去谷歌输入“堆栈溢出”并右键单击第一个链接并单击“在新窗口中打开”它在 IE 而不是 Chrome
中打开。这是我编码不正确,还是我的计算机上的设置不正确

===编辑===

这真的很烦人。我已经知道浏览器是 IE,但我之前运行良好。当我单击一个链接时,它会在 chrome 中打开。我当时正在使用sharp develop
制作应用程序,因为我无法启动c# express。我做了一个全新的 Windows
安装,因为我在我的应用程序中并没有走得太远,所以我决定重新开始,现在我遇到了这个问题。这就是为什么我不确定它是否是我的电脑。为什么点击链接时 IE
会启动整个浏览器,而不是简单地在默认浏览器中打开新链接?

delphi – 在默认浏览器中打开网页,在url中使用双引号(“)

delphi – 在默认浏览器中打开网页,在url中使用双引号(“)

当我尝试打开链接中有双引号(“)的任何网站时,对于ex.user.PHP?name =”stackoverflow“它只是削减”或者有时它会将我重定向到Google !?
二手代码:
ShellExecute(0,'open',PChar('open'),PChar(URL),nil,SW_SHOW) ;

解决方法

您需要使用包含http://的完全限定URL,并通过将双引号(“)替换为”来转义/编码URL.

你也传递了错误的参数.

请参阅MSDN:Use ShellExecute to launch the default Web browser

例:

procedure TForm1.Button1Click(Sender: TObject);
var
  URL: string;
begin
  URL := 'http://www.user.com/?name="stackoverflow"';
  URL := StringReplace(URL,'"','%22',[rfReplaceAll]);
  ShellExecute(0,SW_SHOWnorMAL);
end;

您应始终对URL参数进行编码,而不仅仅是双引号.您可以将Indy与TIdURI.URLEncode – IdURI单位一起使用.
您还可以使用HTTPApp单元中的HTTPEncode对URL中的每个参数进行编码.

注意TIdURI.URLEncode会编码吗?和&分隔符也.所以我认为用HTTPEncode分别编码每个参数是个更好的主意,例如:

URL := 'http://www.user.com/?param1=%s&param2=%s';
URL := Format(URL,[
  HTTPEncode('"stackoverflow.com"'),HTTPEncode('hello word!')]);
// output: http://www.user.com/?param1=%22stackoverflow.com%22&param2=hello+word!

我们今天的关于默认浏览器中的OSX Swift打开URL贴吧热门评论的分享已经告一段落,感谢您的关注,如果您想了解更多关于android – 在WebView中打开URL而不是默认浏览器、c# – 如何在WinForm的浏览器中打开默认Windows浏览器并将HTTP发布数据发送到打开的URL?、C#如何在默认浏览器中打开、delphi – 在默认浏览器中打开网页,在url中使用双引号(“)的相关信息,请在本站查询。

本文标签: