Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách mở App Store từ ứng dụng iOS

Giới thiệu

Bài viết này hướng dẫn mở App Store và hiển thị trang chi tiết của một ứng dụng (ví dụ: Facebook) từ trong ứng dụng iOS của bạn.

Các bước thực hiện

Bước 1: Tạo dự án

Xcode → New Project → Single View Application → Tên "OpenAppStore".

Bước 2: Thêm Button vào Storyboard

Cách mở App Store từ ứng dụng iOS

Bước 3: Tạo IBAction

@IBAction func openAppstoreClicked(_ sender: Any) { }

Bước 4: Viết code mở App Store

@IBAction func openAppstoreClicked(_ sender: Any) {
    // URL mẫu cho Facebook (App ID: 284882215)
    let urlString = "https://itunes.apple.com/app/id284882215"
    
    if let url = URL(string: urlString) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

Giải thích URL App Store

  • Định dạng chuẩn: https://itunes.apple.com/app/id
  • Tìm App ID: Trong App Store Connect hoặc URL trang web App Store (sau id).
  • Ví dụ Facebook: id284882215.
  • Có thể thêm tham số: ?mt=8 (chỉ định iOS), &at=1000lxxx (affiliate token).

Bước 5: Chạy thử

Bấm button → App Store mở trang ứng dụng:

Cách mở App Store từ ứng dụng iOS

Mở trang đánh giá (Rate/Review) trực tiếp

func openAppStoreReviewPage(appId: String) {
    let urlString = "https://itunes.apple.com/app/id\(appId)?action=write-review"
    if let url = URL(string: urlString) {
        UIApplication.shared.open(url)
    }
}

Sử dụng SKStoreProductViewController (iOS 6+)

Mở App Store **bên trong app** (không chuyển sang app App Store riêng):

import StoreKit

func showAppStoreInApp(appId: String) {
    let storeVC = SKStoreProductViewController()
    storeVC.delegate = self
    let parameters = [SKStoreProductParameterITunesItemIdentifier: appId]
    storeVC.loadProduct(withParameters: parameters) { success, error in
        if success {
            self.present(storeVC, animated: true)
        }
    }
}

// Delegate để đóng
extension ViewController: SKStoreProductViewControllerDelegate {
    func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
        viewController.dismiss(animated: true)
    }
}

Lưu ý

  • URL itunes.apple.com chuyển hướng đến apps.apple.com (mới).
  • Luôn kiểm tra canOpenURL nếu dùng custom scheme (ví dụ: itms-apps://).
  • SKStoreProductViewController giữ người dùng trong app, tỷ lệ đánh giá cao hơn.