I am creating an iOS Application iMessage Extension.
According to Example by Apple, I creating a message according to provided logic
guard let url: URL = URL(string: "http://www.google.com") else { return }
let message = composeMessage(url: url)
activeConversation?.insert(message, completionHandler: { [weak self] (error: Error?) in
guard let error = error else { return }
self?.presentAlert(error: error)
})
also
private func composeMessage(url: URL) -> MSMessage {
let layout = MSMessageTemplateLayout()
layout.caption = "caption"
layout.subcaption = "subcaption"
layout.trailingSubcaption = "trailing subcaption"
let message = MSMessage()
message.url = url
message.layout = layout
return message
}
and
private func presentAlert(error: Error) {
let alertController: UIAlertController = UIAlertController(
title: "Error",
message: error.localizedDescription,
preferredStyle: .alert
)
let cancelAction: UIAlertAction = UIAlertAction(
title: "OK",
style: .cancel,
handler: nil
)
alertController.addAction(cancelAction)
present(
alertController,
animated: true,
completion: nil
)
}
As far as I understand, after message is sent, on a click, Safari browser should be opened.
When I click on a sent message, MessageViewController screen takes place in whole screen, without opening safari or another app.
Where is the problem? How can I achieve desired functionality?
Here is the code I use to open a URL from a iMessage extension. It is currently working to open the Music app in the WATUU iMessage application. For instance with the URL
"https://itunes.apple.com/us/album/as%C3%AD/1154300311?i=1154300401&uo=4&app=music"
This functionality currently works in iOS 10, 11 and 12
func openInMessagingURL(urlString: String){
if let url = NSURL(string:urlString){
let context = NSExtensionContext()
context.open(url, completionHandler: nil)
var responder = self as UIResponder?
while (responder != nil){
if responder?.responds(to: Selector("openURL:")) == true{
responder?.perform(Selector("openURL:"), with: url)
}
responder = responder!.next
}
}
}
UPDATE FOR SWIFT 4
func openInMessagingURL(urlString: String){
if let url = URL(string:urlString){
let context = NSExtensionContext()
context.open(url, completionHandler: nil)
var responder = self as UIResponder?
while (responder != nil){
if responder?.responds(to: #selector(UIApplication.open(_:options:completionHandler:))) == true{
responder?.perform(#selector(UIApplication.open(_:options:completionHandler:)), with: url)
}
responder = responder!.next
}
}
}
I think safari Browser only opens for macOS. This worked for me:
override func didSelectMessage(message: MSMessage, conversation: MSConversation) {
if let message = conversation.selectedMessage {
// message selected
// Eg. open your app:
let url = // your apps url
self.extensionContext?.openURL(url, completionHandler: { (success: Bool) in
})
}
}
Using the technique shown by Julio Bailon
Fixed for Swift 4 and that openURL has been deprecated.
Note that the extensionContext?.openURL technique does not work from an iMessage extension - it only opens your current app.
I have posted a full sample app showing the technique on GitHub with the relevant snippet here:
let handler = { (success:Bool) -> () in
if success {
os_log("Finished opening URL")
} else {
os_log("Failed to open URL")
}
}
let openSel = #selector(UIApplication.open(_:options:completionHandler:))
while (responder != nil){
if responder?.responds(to: openSel ) == true{
// cannot package up multiple args to openSel so we explicitly call it on the iMessage application instance
// found by iterating up the chain
(responder as? UIApplication)?.open(url, completionHandler:handler) // perform(openSel, with: url)
return
}
responder = responder!.next
}
It seems it is not possible to open an app from a Message Extension, except the companion app contained in the Workspace. We have tried to open Safari from our Message Extension, it did not work, this limitation seems by design.
You could try other scenari to solve your problem :
Webview in Expanded Message Extension
You could have a Webview in your Message Extension, and when you click
on a message, you could open the Expanded mode and open you Url in the
Webview.
The user won't be in Safari, but the page will be embedded in your Message Extension.
Open the Url in the Companion App
On a click on the message, you could open your Companion app (through
the Url Scheme with MyApp://?myParam=myValue) with a special parameter
; the Companion app should react to this parameter and could redirect
to Safari through OpenUrl.
In this case, you'll several redirects before the WebPage, but it should allow to go back to the conversation.
We have also found that we could instance a SKStoreProductViewController in a Message Extension, if you want to open the Apple Store right in Messages and let the user buy items.
If you only need to insert a link, then you should use activeConversation.insertText and insert the link. Touching the message will open Safari.
openURL in didSelectMessage:conversation: by using extensionContext
handle the URL scheme in your host AppDelegate
Related
I'm adding an iMessage extension target to my app. The extension is supposed to send a message that has a url attribute. The behaviour I'm expecting when a user touches the message is to open the browser using the url attribute of the message.
I have a button in my messageView which executes this code:
#IBAction func labelButton(_ sender: Any) {
let layout = MSMessageTemplateLayout()
layout.imageTitle = "iMessage Extension"
layout.caption = "Hello world!"
layout.subcaption = "Test sub"
guard let url: URL = URL(string: "https://google.com") else { return }
let message = MSMessage()
message.layout = layout
message.summaryText = "Sent Hello World message"
message.url = url
activeConversation?.insert(message, completionHandler: nil)
}
If I touch the message, it expands the MessageViewController
I have then added this:
override func didSelect(_ message: MSMessage, conversation: MSConversation) {
if let message = conversation.selectedMessage {
// message selected
// Eg. open your app:
self.extensionContext?.open(message.url!, completionHandler: nil)
}
}
And now, when I touch the message, it opens my main app but still not my browser.
I have seen on another post (where I cannot comment, thus I opened this post) that it is impossible to open in Safari but I have a news app which inserts links to articles and allows with a click on the message to open the article in a browser window, while the app is installed.
So, can someone please tell how I can proceed to force opening the link in a browser window?
Thank you very much.
Here is a trick to insert a link in a message. It does not allow to create an object that has an url attribute but just to insert a link directly which will open in the default web browser.
activeConversation?.insertText("https://google.com", completionHandler: nil)
I have published a sample on github showing how to launch a URL from inside an iMessage extension. It just uses a fixed URL but the launching code is what you need.
Copying from my readme
The obvious thing to try is self.extensionContext.open which is documented as Asks the system to open a URL on behalf of the currently running app extension.
That doesn't work. However, you can iterate back up the responder chain to find a suitable handler for the open method (actually the iMessage instance) and invoke open with that object.
This approach works for URLs which will open a local app, like settings for a camera, or for web URLs.
The main code
#IBAction public func onOpenWeb(_ sender: UIButton) {
guard let url = testUrl else {return}
// technique that works rather than self.extensionContext.open
var responder = self as UIResponder?
let handler = { (success:Bool) -> () in
if success {
os_log("Finished opening URL")
} else {
os_log("Failed to open URL")
}
}
let openSel = #selector(UIApplication.open(_:options:completionHandler:))
while (responder != nil){
if responder?.responds(to: openSel ) == true{
// cannot package up multiple args to openSel so we explicitly call it on the iMessage application instance
// found by iterating up the chain
(responder as? UIApplication)?.open(url, completionHandler:handler) // perform(openSel, with: url)
return
}
responder = responder!.next
}
}
I have a Safari share extension where I want the ability to open the main app from within the extension. The user is presented with an alert where they have the option to open the app.
func openAppHandler() {
self.extensionContext?.completeRequest(returningItems: []) { (success) in
if let url = URL(string: "myapp://...") {
self.extensionContext?.open(url, completionHandler: nil)
}
}
}
The alert appears after the method didSelectPost() is called, and as you can see it occurs in the background priority completion block for the extension. The open method says in it's docs "In iOS 8, only the Today extension point (used for creating widgets) supports this method." I'm guessing it's still the case that it's still not supported in the Safari Share Extension.
Does anyone know of a way to open my main app from a share extension?
I found a solution here. I'm not sure if this is technically ok with Apple, but it works just as I need it to.
#objc func openURL(_ url: URL) {
return
}
func openContainerApp() {
var responder: UIResponder? = self as UIResponder
let selector = #selector(MyViewController.openURL(_:))
while responder != nil {
if responder!.responds(to: selector) && responder != self {
responder!.perform(selector, with: URL(string: "myapp://url")!)
return
}
responder = responder?.next
}
}
First of all I'm new developing with Swift, I have an Objective C background, but I'm mainly an Android developer.
Actually I'm developing an app in Swift 3 and Xcode 8. I need to add to this application the new rich push notification system of Apple.
I have been able to add a local rich notification example with pics, videos and gifs. But I need to show remote notifications with pics hosted on a typical Internet server.
To launch local notifications I'm using this code:
#IBAction func launchPicNotification(sender: UIButton) {
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
let url = Bundle.main.url(forResource:"foto", withExtension: "jpg")
let attachment = try? UNNotificationAttachment(identifier: "Notification",
url: url!,
options: [:])
if let attachment = attachment {
print("Yes")
content.attachments.append(attachment)
}else{
print("No")
}
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 10.0, repeats: false)
let request = UNNotificationRequest(identifier:"identificador", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request){(error) in
if (error != nil){
//handle here
}
}
}
I need to load a remote jpg file as attached image. Does somebody know how can I load a remote file instead of load a local picture?
Thanks
I added an extension to UIImage to handle this. Once you create a UIImage from the downloaded data, you can call this function to create a local URL.
extension UIImage {
func createLocalURL() -> URL? {
guard let data = UIImagePNGRepresentation(self) else {
print("Coule not get UIImagePNGRepresentation Data for photo")
return nil
}
let localUrl = self.getDocumentsDirectory().appendingPathComponent("copy.png")
do {
try data.write(to: localUrl)
} catch let error {
print("Failed to write to URL")
print(error)
}
return localUrl
}
}
I am trying to implement a feature in an App that shows an alert when the internet connection is not available.
The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.
I am using Swift and Xcode.
Using UIApplication.openSettingsURLString
Update for Swift 5.1
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
Swift 4.2
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
⚠️ Be careful!
This answer is based on undocumented APIs and recently (since iOS12) Apple is rejecting apps with this approach.
Original answer below
Swift 5
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
Swift 4
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
NOTE: The following method works for all the versions below iOS 11, for higher versions the app might get rejected since it's a private API
Sometimes we want to take a user to settings other than our app settings.
The following method will help you achieve that:
First, configure the URL Schemes in your project. You will find it in Target -> Info -> URL Scheme. click on + button and type prefs in URL Schemes
Swift 5
UIApplication.shared.open(URL(string: "App-prefs:Bluetooth")!)
Swift 3
UIApplication.shared.open(URL(string:"App-Prefs:root=General")!, options: [:], completionHandler: nil)
Swift
UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General")!)
Objective-C
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"prefs:root=General"]];
and following are all the available URLs
**On IOS < 12 **
prefs:root=General&path=About
prefs:root=General&path=ACCESSIBILITY
prefs:root=AIRPLANE_MODE
prefs:root=General&path=AUTOLOCK
prefs:root=General&path=USAGE/CELLULAR_USAGE
prefs:root=Brightness
prefs:root=Bluetooth
prefs:root=General&path=DATE_AND_TIME
prefs:root=FACETIME
prefs:root=General
prefs:root=General&path=Keyboard
prefs:root=CASTLE
prefs:root=CASTLE&path=STORAGE_AND_BACKUP
prefs:root=General&path=INTERNATIONAL
prefs:root=LOCATION_SERVICES
prefs:root=ACCOUNT_SETTINGS
prefs:root=MUSIC
prefs:root=MUSIC&path=EQ
prefs:root=MUSIC&path=VolumeLimit
prefs:root=General&path=Network
prefs:root=NIKE_PLUS_IPOD
prefs:root=NOTES
prefs:root=NOTIFICATIONS_ID
prefs:root=Phone
prefs:root=Photos
prefs:root=General&path=ManagedConfigurationList
prefs:root=General&path=Reset
prefs:root=Sounds&path=Ringtone
prefs:root=Safari
prefs:root=General&path=Assistant
prefs:root=Sounds
prefs:root=General&path=SOFTWARE_UPDATE_LINK
prefs:root=STORE
prefs:root=TWITTER
prefs:root=FACEBOOK
prefs:root=General&path=USAGE prefs:root=VIDEO
prefs:root=General&path=Network/VPN
prefs:root=Wallpaper
prefs:root=WIFI
prefs:root=INTERNET_TETHERING
prefs:root=Phone&path=Blocked
prefs:root=DO_NOT_DISTURB
On IOS 13
App-prefs:General&path=About
App-prefs:AIRPLANE_MODE
App-prefs:General&path=AUTOLOCK
App-prefs:Bluetooth
App-prefs:General&path=DATE_AND_TIME
App-prefs:FACETIME
App-prefs:General
App-prefs:General&path=Keyboard
App-prefs:CASTLE
App-prefs:CASTLE&path=STORAGE_AND_BACKUP
App-prefs:General&path=INTERNATIONAL
App-prefs:MUSIC
App-prefs:NOTES
App-prefs:NOTIFICATIONS_ID
App-prefs:Phone
App-prefs:Photos
App-prefs:General&path=ManagedConfigurationList
App-prefs:General&path=Reset
App-prefs:Sounds&path=Ringtone
App-prefs:Sounds
App-prefs:General&path=SOFTWARE_UPDATE_LINK
App-prefs:STORE
App-prefs:Wallpaper
App-prefs:WIFI
App-prefs:INTERNET_TETHERING
App-prefs:DO_NOT_DISTURB
Not tested
App-prefs:TWITTER (??)
App-prefs:FACEBOOK (??)
App-prefs:NIKE_PLUS_IPOD (??)
Note: Network setting will not be opened in a simulator, but the link will work on a real device.
SWIFT 5
if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsUrl)
}
In iOS 8+ you can do the following:
func buttonClicked(sender:UIButton)
{
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString))
}
Swift 4
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(settingsUrl)
Using #vivek's hint I develop an utils class based on Swift 3, hope you appreciate!
import Foundation
import UIKit
public enum PreferenceType: String {
case about = "General&path=About"
case accessibility = "General&path=ACCESSIBILITY"
case airplaneMode = "AIRPLANE_MODE"
case autolock = "General&path=AUTOLOCK"
case cellularUsage = "General&path=USAGE/CELLULAR_USAGE"
case brightness = "Brightness"
case bluetooth = "Bluetooth"
case dateAndTime = "General&path=DATE_AND_TIME"
case facetime = "FACETIME"
case general = "General"
case keyboard = "General&path=Keyboard"
case castle = "CASTLE"
case storageAndBackup = "CASTLE&path=STORAGE_AND_BACKUP"
case international = "General&path=INTERNATIONAL"
case locationServices = "LOCATION_SERVICES"
case accountSettings = "ACCOUNT_SETTINGS"
case music = "MUSIC"
case equalizer = "MUSIC&path=EQ"
case volumeLimit = "MUSIC&path=VolumeLimit"
case network = "General&path=Network"
case nikePlusIPod = "NIKE_PLUS_IPOD"
case notes = "NOTES"
case notificationsId = "NOTIFICATIONS_ID"
case phone = "Phone"
case photos = "Photos"
case managedConfigurationList = "General&path=ManagedConfigurationList"
case reset = "General&path=Reset"
case ringtone = "Sounds&path=Ringtone"
case safari = "Safari"
case assistant = "General&path=Assistant"
case sounds = "Sounds"
case softwareUpdateLink = "General&path=SOFTWARE_UPDATE_LINK"
case store = "STORE"
case twitter = "TWITTER"
case facebook = "FACEBOOK"
case usage = "General&path=USAGE"
case video = "VIDEO"
case vpn = "General&path=Network/VPN"
case wallpaper = "Wallpaper"
case wifi = "WIFI"
case tethering = "INTERNET_TETHERING"
case blocked = "Phone&path=Blocked"
case doNotDisturb = "DO_NOT_DISTURB"
}
enum PreferenceExplorerError: Error {
case notFound(String)
}
open class PreferencesExplorer {
// MARK: - Class properties -
static private let preferencePath = "App-Prefs:root"
// MARK: - Class methods -
static func open(_ preferenceType: PreferenceType) throws {
let appPath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
if let url = URL(string: appPath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
throw PreferenceExplorerError.notFound(appPath)
}
}
}
This is very helpful since that API's will change for sure and you can refactor once and very fast!
The first response from App-Specific URL Schemes worked for me on iOS 10.3.
if let appSettings = URL(string: UIApplicationOpenSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
UIApplication.shared.open(appSettings)
}
}
App-Prefs:root=Privacy&path=LOCATION worked for me for getting to general location settings. Note: only works on a device.
iOS 12+
The open(url:options:completionHandler:) method has been updated to include a non-nil options dictionary, which as of this post only contains one possible option of type UIApplication.OpenExternalURLOptionsKey (in the example).
#objc func openAppSpecificSettings() {
guard let url = URL(string: UIApplication.openSettingsURLString),
UIApplication.shared.canOpenURL(url) else {
return
}
let optionsKeyDictionary = [UIApplication.OpenExternalURLOptionsKey(rawValue: "universalLinksOnly"): NSNumber(value: true)]
UIApplication.shared.open(url, options: optionsKeyDictionary, completionHandler: nil)
}
Explicitly constructing a URL, such as with "App-Prefs", has gotten some apps rejected from the store.
word of warning: the prefs:root or App-Prefs:root URL schemes are considered private API. Apple may reject you app if you use those, here is what you may get when submitting your app:
Your app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change. Continuing to use or conceal non-public APIs in future submissions of this app may result in the termination of your Apple Developer account, as well as removal of all associated apps from the App Store.
Next Steps
To resolve this issue, please revise your app to provide the associated functionality using public APIs or remove the functionality using the "prefs:root" or "App-Prefs:root" URL scheme.
If there are no alternatives for providing the functionality your app requires, you can file an enhancement request.
in ios10/ Xcode 8 in simulator:
UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!)
works
UIApplication.shared.openURL(URL(string:"prefs:root=General")!)
does not.
I have seen this line of code
UIApplication.sharedApplication() .openURL(NSURL(string:"prefs:root=General")!)
is not working, it didn't work for me in ios10/ Xcode 8, just a small code difference, please replace this with
UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=General")!)
Swift3
UIApplication.shared.openURL(URL(string:"prefs:root=General")!)
Replace with
UIApplication.shared.openURL(URL(string:"App-Prefs:root=General")!)
Hope it helps.
Cheers.
Adding to #Luca Davanzo
iOS 11, some permissions settings have moved to the app path:
iOS 11 Support
static func open(_ preferenceType: PreferenceType) throws {
var preferencePath: String
if #available(iOS 11.0, *), preferenceType == .video || preferenceType == .locationServices || preferenceType == .photos {
preferencePath = UIApplicationOpenSettingsURLString
} else {
preferencePath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
}
if let url = URL(string: preferencePath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
throw PreferenceExplorerError.notFound(preferencePath)
}
}
SWIFT 4
This could take your app's specific settings, if that's what you're looking for.
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
As above #niravdesai said App-prefs.
I found that App-Prefs: works for both iOS 9, 10 and 11. devices tested.
where as prefs: only works on iOS 9.
UIApplication.open(_:options:completionHandler:) must be used from main thread only
Solution:
if let appSettings = URL(string: UIApplication.openSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
DispatchQueue.main.async {
UIApplication.shared.open(appSettings)
}
}
}
First I don't know how to get the link before I submit my app, and if the link is for each country app store or is it universal?
Also I don't know if the way to do it is just by putting the link there like:
#IBAction func rate(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string : "webLinkHere")!)
}
Or should I use another way to do this?
Thanks
Try This, change appId in your method by your App ID
Swift 5
import StoreKit
func rateApp() {
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
} else if let url = URL(string: "itms-apps://itunes.apple.com/app/" + "appId") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
Swift 3 \ 4
func rateApp() {
guard let url = URL(string: "itms-apps://itunes.apple.com/app/" + "appId") else {
return
}
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
id959379869 This is the id when you go on your Itune page of your app
Example :
https://itunes.apple.com/fr/app/hipster-moustache/id959379869?mt=8
How get the ID :
Itunesconnect account
My Apps
Click on "+" Button
New iOS App
Fill require details
After filling all details goto your App
Click on More Button
View on AppStore
It will redirect you to your App URL this will be universal
Look Http URL
This is working the best for me.
Directs the user straight to the 'Write A Review' composer of the application.
Swift 3.1 (Support for iOS10 and below)
Introduces new action=write-review
let appID = "959379869"
if let checkURL = URL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appID)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8") {
open(url: checkURL)
} else {
print("invalid url")
}
...
func open(url: URL) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
print("Open \(url): \(success)")
})
} else if UIApplication.shared.openURL(url) {
print("Open \(url)")
}
}
Tested and works on Swift 2.2
let appID = "959379869" // Your AppID
if let checkURL = NSURL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appID)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8") {
if UIApplication.sharedApplication().openURL(checkURL) {
print("url successfully opened")
}
} else {
print("invalid url")
}
Swift 4
let url = URL(string: "itms-apps:itunes.apple.com/us/app/apple-store/id\(YOURAPPID)?mt=8&action=write-review")!
UIApplication.shared.openURL(url)
Now after iOS 10.3+
The SKStoreReviewController allows users to rate an app directly from within the app through a dialog box. The only downsite is that you can only request StoreKit to display the dialog, but can't be sure if it will.
import StoreKit
func requestToRate() {
SKStoreReviewController.requestReview()
}
Swift 5.1: The following function sends your user directly to the review section of ANY store, not just on the American one:
func rateApp(id : String) {
guard let url = URL(string : "itms-apps://itunes.apple.com/app/id\(id)?mt=8&action=write-review") else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
Usage:
rateApp(id: "1287000522")
Important Note: This doesn't work on simulator! Test it on a real device.
You can use the following function and replace the APP_ID with your one. Calling this function will open the app in app store link and user will see the Review page where he can click and write a review easily.
func rateApp(){
UIApplication.sharedApplication().openURL(NSURL(string : "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(APP_ID)&onlyLatestVersion=true&pageNumber=0&sortOrdering=1)")!);
}
For iOS 10.3+ you can use SKStoreReviewController with simple dialog, and choose rating in alert-style window. To use it, you should import StoreKit library. So, universal way to rate your app inside itself is like this:
import StoreKit
func rateApp(){
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
} else {
guard let url = URL(string: "itms-apps://itunes.apple.com/ru/app/cosmeteria/id1270174484") else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
And when you try to launch it in simulator, you won't see App Store window, so try it on device and it gonna work. This way covers all iOS versions, using all abilities. And the part of path in you application address "/us/app" means your App Store localisation, for example "us" means USA. You can easily find your app id in address string just by opening app in App Store in any browser.To get the link, just copy address in browser. Changing "https://" for "itms-apps://" lets you to open app in App Store application, while "https" opens web page in Safari
WARNING: If you are running your app on a simulator
UIApplication.sharedApplication().openURL(NSURL(string : "url")!)
will not work because there is no app store in the simulator. In order to test this functionality you must run your app on a device.
Swift 3
func rateApp(){
UIApplication.shared.open(URL(string : "itms-apps://itunes.apple.com/app/id959379869")!, options: [:]) { (done) in
// Handle results
}}
id959379869 This is the id when you go on your iTunes page of your app
Goto your itunesconnect account -> My Apps -> Click on "+" Button ->New iOS App -> Fill require details -> After filling all details goto your App -> Click on More Button -> View on AppStore -> it will redirect you to your App URL this will be universal & will be same after your app goes live .
All the above answers are not best practices they might be affecting your app store ratings. For best practice use the below code.
func ReviewAppController() {
let alert = UIAlertController(title: "Feedback", message: "Are you enjoying our App?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismis", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Yes, i Love it!", style: .default, handler: {_ in
SKStoreReviewController.requestReview()
}))
alert.addAction(UIAlertAction(title: "No, this sucks!", style: .default, handler: {_ in
//Collect feedback
}))
present(alert, animated: true)
}
This link opens your app page in the App Store and then presents the write review sheet.
itms-apps://itunes.apple.com/app/id[APP_ID]?action=write-review
You can find the APP_ID in the App Store Connect under the details of your app as Apple ID.
In case you want to directly write a review rather than just open an app page:
if let url = URL(string: "https://itunes.apple.com/in/app/\(yourappname)/id\(yourAppleAppId)?ls=1&mt=8&action=write-review") {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
// Earlier versions
if UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.openURL(url as URL)
}
}
}