Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

ios - How to open fb and instagram app by tapping on button in Swift

How can I open Facebook and Instagram app by tapping on a button in swift? Some apps redirect to the Facebook app and open a specific page. How can I do the same thing?

I found it:

var url = NSURL(string: "itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4")

if UIApplication.sharedApplication().canOpenURL(url!) {
  UIApplication.sharedApplication().openURL(url!)
}

but I have to know the app URL. Other examples were in ObjectiveC, which I don't know =/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update for Swift 4 and iOS 10+

OK, there are two easy steps to achieve this in Swift 3:

First, you have to modify Info.plist to list instagram and facebook with LSApplicationQueriesSchemes. Simply open Info.plist as a Source Code, and paste this:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>instagram</string>
    <string>fb</string>
</array>

After that, you can open instagram and facebook apps by using instagram:// and fb://. Here is a complete code for instagram and you can do the same for facebook, you can link this code to any button you have as an Action:

@IBAction func InstagramAction() {

    let Username =  "instagram" // Your Instagram Username here
    let appURL = URL(string: "instagram://user?username=(Username)")!
    let application = UIApplication.shared

    if application.canOpenURL(appURL) {
        application.open(appURL)
    } else {
        // if Instagram app is not installed, open URL inside Safari
        let webURL = URL(string: "https://instagram.com/(Username)")!
        application.open(webURL)
    }

}

For facebook, you can use this code:

let appURL = URL(string: "fb://profile/(Username)")!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...