2017-04-12 152 views
1

我想在手機上啓用一個功能,允許用戶單擊共享,然後他們將能夠給他們的朋友發短信,該信息默認包含該應用程序(就在用戶點擊共享之前)。我無法弄清楚如何做到這一點 - 每當我搜索如何做到這一點時,我所得到的都是關於如何在手機照片庫或相機中共享圖像的教程/答案。任何想法如何做到這一點!獲取iOS/swift中當前屏幕的截圖

+1

截圖功能已經存在於所有的iphones中。因此,截圖並分享它。 – KAR

回答

2

//從截圖創建圖像

UIGraphicsBeginImageContext(view.frame.size) 
view.layer.renderInContext(UIGraphicsGetCurrentContext()) 
let image = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

//共享圖像

var imagesToShare = [AnyObject]() 
imagesToShare.append(image) 

let activityViewController = UIActivityViewController(activityItems: imagesToShare , applicationActivities: nil) 
activityViewController.popoverPresentationController?.sourceView = self.view 
presentViewController(activityViewController, animated: true, completion: nil) 
3
UIGraphicsBeginImageContext(self.view.bounds.size) 
self.view.drawHierarchy(in: view.bounds, afterScreenUpdates: false) 
let image = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
+0

使用此代碼並從中獲取uiimage,然後可以繼續共享。 –

1

共享您的屏幕用戶點擊分享之前,首先你會需要將屏幕視圖更改爲圖像並共享。

要將您的視圖更改爲圖像,您可以在代碼中添加此擴展名。

//UIView extension which converts the UIView into an image. 
extension UIView { 
    func toImage() -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale) 

     drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true) 

     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image 
    } 
} 

通過你的ViewController的觀點有,例如:

let imageToShare = self.view.toImage() 

    let activityItems : NSMutableArray = []() 
     activityItems.addObject(imageToShare) 


    let activityVC = UIActivityViewController(activityItems:activityItems as [AnyObject] , applicationActivities: nil) 
       self.presentViewController(activityVC, animated: true, completion: nil) 

我希望這可以幫助你。