URL 未在 UIWebView 上打开?

URL not opening on UIWebView?

我尝试用 IBAction 打开网页

@IBAction func Start(sender: AnyObject) {
    self.viewWebpage("http://www.xxxxx.xx")
}

func viewWebpage(webpage: String)
{
    let url = NSURL.fileURLWithPath(webpage)
    println(webpage)
    let request = NSURLRequest(URL: url!)
    self.viewPage.loadRequest(request)
   // self.viewPage.reload()
}

当我将 url 的功能更改为

时,我尝试打开的网页有效
let url = NSURL(string: "http://www.xxxxxx.xx")

我的错误在哪里? println() 打印出 wright url

问题在于:

let url = NSURL.fileURLWithPath(webpage)

您正在将网络 url 转换为文件系统 url(url 系统本身包含的文件)。所以它不起作用,你需要将其更改为:

let url = NSURL(string: webpage)

根据NSURL Class Reference

+ fileURLWithPath:

Initializes and returns a newly created NSURL object as a file URL with a specified path. Declaration

Swift

class func fileURLWithPath(_ path: String) -> NSURL?

Objective-C

+ (NSURL *)fileURLWithPath:(NSString *)path

Parameters

path

The path that the NSURL object will represent. path should be a valid system path. If path begins with a tilde, it must first be expanded with stringByExpandingTildeInPath. If path is a relative path, it is treated as being relative to the current working directory.

Passing nil for this parameter produces an exception.

Return Value

An NSURL object initialized with path.

Discussion

This method assumes that path is a directory if it ends with a slash. If path does not end with a slash, the method examines the file system to determine if path is a file or a directory. If path exists in the file system and is a directory, the method appends a trailing slash. If path does not exist in the file system, the method assumes that it represents a file and does not append a trailing slash.

As an alternative, consider using fileURLWithPath:isDirectory:, which allows you to explicitly specify whether the returned NSURL object represents a file or directory.