iOS

링크 공유 & 이동 구현하기

GREEN.1229 2021. 11. 23. 22:00

안녕하세요. 그린입니다🟢

이번 포스팅에서는 iOS에서 기본 기능으로 여러모로 잘 사용되고 있는

링크 공유 및 링크 이동하기에 대해 구현해보겠습니다💁🏻

 

다들 앱을 사용하시다가 링크복사를 통해 링크 공유하기 그리고 버튼을 눌러서 특정 웹페이지로 이동하는 등의 경험은
아주아주 당연하고 많이 있으실겁니다!
그래서 이 당연한건 당연하게 SwiftUI로 한번 도전해보겠습니다.
사실 뷰만 SwiftUI일 뿐이지 그 링크에 대한 액션은 특별할건 없어요..😅
스택오버플로나 구글링만 해봐도 링크 공유와 이동에 대해선 너무너무 공식처럼 많이 나오기에 이걸 잘 활용해서
저는 조금 더 구조적으로 만들어보겠습니다🙋🏻

우선 어떤 구현을 할것인지 시뮬레이터 동작을 보시죠!

시뮬레이터 동작

자 공유를 누르면 시뮬레이터여서 카톡이나 다른 다양한 연동된 앱은 나오지 않지만 디바이스를 연결한다면 흔히 보던

기본적인 공유 기능을 확인할 수 있습니다.

우선 풀스크린으로 띄우지 않도록 반정도만 나오도록 모달이 구성되고 공유할 수 있습니다.

그리고 링크 이동 버튼을 클릭하면 지정된 그 URL로 이동하게 됩니다.

 

그럼 코드를 보실까요? 💁🏻

전체 소스코드

import SwiftUI

struct ContentView: View {
  var body: some View {
    Button(
      "링크 공유",
      action: {
        buttonAction("https://www.google.com", .share)
      }
    )
    Button(
      "링크 이동",
      action: {
        buttonAction("https://www.google.com", .link)
      }
    )
  }
  
  private enum Coordinator {
    static func topViewController(
      _ viewController: UIViewController? = nil
    ) -> UIViewController? {
      let vc = viewController ?? UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController
      
      if let navigationController = vc as? UINavigationController {
        return topViewController(navigationController.topViewController)
      } else if let tabBarController = vc as? UITabBarController {
        return tabBarController.presentedViewController != nil ?
        topViewController(
          tabBarController.presentedViewController
        ) : topViewController(
          tabBarController.selectedViewController
        )
      } else if let presentedViewController = vc?.presentedViewController {
        return topViewController(presentedViewController)
      }
      return vc
    }
  }
  
  private enum Method: String {
    case share
    case link
  }
  
  private func buttonAction(_ stringToURL: String, _ method: Method) {
    let shareURL: URL = URL(string: stringToURL)!
    
    if method == .share {
      let activityViewController = UIActivityViewController(activityItems: [shareURL], applicationActivities: nil)
      let viewController = Coordinator.topViewController()
      activityViewController.popoverPresentationController?.sourceView = viewController?.view
      viewController?.present(activityViewController, animated: true, completion: nil)
    } else {
      UIApplication.shared.open(URL(string: stringToURL)!)
    }
  }
}

전체적으로는 요렇게 구조를 가져가봤습니다.

우선 SwiftUI를 통해 버튼 두개를 구성합니다.

해당하는 버튼에 대한 액션을 만들기 전 공유 모달에 대해 컨트롤해주는 메서드와 어떤 버튼에 대한 동작을 다르게 할지에 대해 Enum 타입으로 생성해줍니다.

우선 Coordinator에는 topVC 메서드를 정의해줍니다.

이 메서드가 호출되면 공유 모달이 윈도우에 맨 상단으로 올라가게 되고 흐름과 기능을 가져갑니다.

그리고 버튼이 눌렸을때 buttonAction이라는 메서드에서는 URL과 method를 받습니다.

문자열을 URL로 변경해주고 공유일 때 UIActivityVC로 어떤 뷰컨이 될지 정해줍니다.

그리고 뷰를 띄워줍니다.

만약 else 구문으로 간다면 링크 이동에 대한 액션을 취해줘야함으로 UIApplication의 open 메서드를 통해 이동시켜줍니다.

마무리

이번에는 학습보다 구현을 하며 조금 변형시킨걸 스스로 기록해보고 필요하신분들이 조금 이해될 수 있도록 정리해봤습니다.

수정될 부분이나 잘못된 부분이 있다면 댓글 남겨주시면 감사하겠습니다🙌

 

[참고자료]

https://stackoverflow.com/questions/37938722/how-to-implement-share-button-in-swift

 

How to implement "share button" in Swift

This is the some peace of code for twitter... I want to know how to get the share action view like we get in iOS stock photos app... @IBAction func twitterButton(sender: AnyObject) { let

stackoverflow.com