swift 3/4 將訊息轉貼到 Line (呼叫 Line App)

2017102711:24

 

 Info.plist 必須新增

        <key>LSApplicationQueriesSchemes</key>
        <array>
        <string>line</string>
        </array>
        
        不然會出現錯誤 http://www.jianshu.com/p/631bd7f12a38
        error: "This app is not allowed to query for scheme line"



程式碼:
func share2Line() {

        let text: String! = "你好吃飯沒!  http://www.nidbox.com"

        // 文字編碼
        let encodeMessage = text.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        
        /*  Line分享的URI scheme格式:line://msg/<CONTENT TYPE>/<CONTENT KEY>
        var lineURL = NSURL(string: "line://msg/text/" + encodeMessage!)
        
        let url = "line://msg/text/" + encodeMessage!
        
        guard let lineURL = URL(string: url) else {
            return
        }
        
        if UIApplication.shared.canOpenURL(lineURL) {

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(lineURL, options: [:], completionHandler: nil)
            } else { //iOS 10.0之前可這樣:
                UIApplication.shared.openURL(lineURL)
            }

        } else { //如果沒裝 line -> 跳到 app store
            let lineURL = URL(string: "itms-apps://itunes.apple.com/app/id443904275")!
            
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(lineURL, options: [:], completionHandler: nil)
            } else { //iOS 10.0之前可這樣:
                UIApplication.shared.openURL(lineURL)
            }

        }
   
    
}




    

另外,也可以透過瀏覽器來傳送(不叫出 Line App):
 
let lineUrl = "http://line.naver.jp/R/msg/text/?\(TITLE)%20%0a\(URL)"

guard let url = URL(string: lineUrl) else {
  return
}
        

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)

} else { //iOS 10.0之前可這樣:
    UIApplication.shared.openURL(url)

}