2015-01-16 56 views

回答

5

試試下面的代碼Web視圖加載後:

編輯:運行模擬器此代碼,然後檢查screenshot.jpeg文件在你的文件app目錄

class ViewController: UIViewController,UIWebViewDelegate { 

let fileDirectory = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true) 

@IBOutlet weak var webView: UIWebView! 

override func viewDidLoad() { 


    var urlPath = "http://www.bbc.com/" 
    let requestUrl = NSURL(string: urlPath) 
    let request = NSURLRequest(URL: requestUrl!) 
    webView.loadRequest(request) 
    webView.delegate = self 

} 

func webViewDidFinishLoad(webView: UIWebView) { 


    if (!webView.loading){ 

     var webViewFrame = webView.frame 

     webView.frame = CGRectMake(webViewFrame.origin.x, webViewFrame.origin.y, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height) 

     UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, false, 0); 
     self.webView.layer.renderInContext(UIGraphicsGetCurrentContext()) 
     var image:UIImage = UIGraphicsGetImageFromCurrentImageContext(); 
     var imageData = UIImageJPEGRepresentation(image, 0.7) 
     var currentFileName = "screenshot.jpeg" 
     var imageFilePath = fileDirectory[0].stringByAppendingPathComponent(currentFileName) 
     var imageFileURL = NSURL(fileURLWithPath: imageFilePath) 
     imageData.writeToURL(imageFileURL!, atomically: false) 
     webView.frame = webViewFrame 
    } 
} 

} 
+0

我在此得到一個錯誤:文件目錄[0] ANW,我試試你這樣的代碼: VAR webViewFrame = webView.frame webView.frame = CGRectMake(webViewFrame.origin.x,webViewFrame.origin.y,webView.scrollView.contentSize.width,web視圖.scrollView.contentSize.height) UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize,false,0); self.webView.layer.renderInContext(UIGraphicsGetCurrentContext()) var image:UIImage = UIGraphicsGetImageFromCurrentImageContext(); webView.frame = webViewFrame 但屏幕截圖並不適用於所有的網頁流量:/就像一個屏幕截圖 –

+0

關於錯誤使用下面的'VAR文件目錄= NSSearchPathForDirectoriesInDomains( .DocumentDirectory,.UserDomainMask,真)'。關於截圖是否確定webview已完全加載?剛剛嘗試過不同的網站和它的工作很好 –

+0

關於第一修正:我們需要編輯這個現在:var imageFileURL = NSURL(fileURLWithPath:imageFilePath) 關於第二:是我是usre,因爲webview是本地在我的項目中我有html文件) 在我的UIActivityViewController中,我調用:image(UIImage),而不是另一個var –