Làm cách nào để thực hiện cuộc gọi, gọi FaceTime và gửi SMS trong ứng dụng sử dụng Swift?

by DaoNM2
122 views

Hiện nay hầu hết các ứng dụng di động đều có tính năng liên lạc nhằm mục đích giúp người sử dụng dễ dàng liên hệ được với bộ phận chăm sóc khách hàng. Để làm được việc này thì Apple có cung cấp một URL Scheme để thực hiện việc này.

URL Scheme Mail

Để có thể sử dụng được tính năng gửi mail thông qua app của Apple chúng ta cần cấu hình dự án cho phép sử dụng URL schemes “mailto” như sau:

Mở file info.plist và thêm Queried URL Shemes -> add item và đặt trường value với giá trị là mailto

Để thực hiện được việc gửi mail chúng ta thực hiện đoạn code như sau:

  func mail(to: String, cc: String = "", subject: String = "", body: String = "") {
        
        var mailURLString: String = "mailto:"
        
        // add to
        mailURLString += to
        
        // add cc
        mailURLString += "?cc=\(cc)"
        
        // add subject
        if let subjectEncode = subject.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            mailURLString += "&subject=\(subjectEncode)"
        }
        
        // add content
        if let bodyEncode = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            mailURLString += "&body=\(bodyEncode)"
        }
        
        // check url
        if let mailURL = URL(string: mailURLString), UIApplication.shared.canOpenURL(mailURL) {
            // open app mail with url
            UIApplication.shared.open(mailURL)
        }
    }

Bây giờ bất kể chỗ nào chúng ta dùng để gửi mail đều có thể call func này để thực hiện việc gửi mail ví dụ như sau:

mail(to: "[email protected]", cc: "[email protected]", subject: "Techover.io", body: "New post")

URL Scheme Phone

Tương tự như Mail việc gọi điện app cũng có 1 scheme cho phép thực hiện việc này.

    func tel(to: String) {
        if let telURL = URL(string: "tel:\(to)"), UIApplication.shared.canOpenURL(telURL) {
            UIApplication.shared.open(telURL)
        }
    }

URL Scheme FaceTime

    func faceTime(to: String) {
        if let telURL = URL(string: "facetime-audio://\(to)"), UIApplication.shared.canOpenURL(telURL) {
            UIApplication.shared.open(telURL)
        }
    }

URL Scheme SMS

    func sms(to: String) {
        if let telURL = URL(string: "sms:\(to)"), UIApplication.shared.canOpenURL(telURL) {
            UIApplication.shared.open(telURL)
        }
    }

Ngoài ra chúng ta còn có thêm các Apple URL Scheme khác như MAP Links , iTunes Links, YouTube Links … Anh em có thể tham khảo thêm tài liệu của Apple ở link sau: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007899-CH1-SW1

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like