AppleWatch 消息 URL 可以硬编码,但不能使用变量 [英] AppleWatch Messages URL works hard coded but not with variables

查看:30
本文介绍了AppleWatch 消息 URL 可以硬编码,但不能使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR 当我将电话号码硬编码到 URL 中时,它会在观看消息中正确打开,但是当我使用变量字符串并在其中以完全相同的方式键入数字时,它不会吨.

TLDR When I hard code phone numbers into a URL it opens in watch messages correctly, but when I use a variable string with the numbers typed in exactly the same way inside of it, it doesn't.

示例:

 NSURL(string: "sms:/open?addresses=8888888888,9999999999,3333333333&body=Test")

以上代码有效,但以下代码无效:

Above code works but below code doesn't:

 let hardCode = "8888888888,9999999999,3333333333"
 NSURL(string: "sms:/open?addresses=\(hardCode)&body=Test")

全部细节:我正在从变量创建一个 URL,以在 Apple Watch 上打开带有预填充内容的消息.我从通讯录中获取电话号码并将它们存储在一个数组中.它们以这种格式提供:

FULL DETAILS: I am making a URL from variables to open messages on the Apple Watch with pre-filled contents. I am getting the phone numbers from the contact book and storing them in an array. They are provided in this format:

(###) ###-#### 但需要是##########

(###) ###-#### but need to be ##########

我通过将电话号码硬编码到 URL 中测试了代码,并且它与所有联系人和完整的正文一起正常工作:

I tested the code by hard-coding phone numbers into the URL and it works properly with all contacts and completed body:

if let urlSafeBody = urlSafeBody, url = NSURL(string: "sms:/open?addresses=8888888888,9999999999,3333333333&body=\(urlSafeBody)") {
        print("FINAL URL: \(url)")
        WKExtension.sharedExtension().openSystemURL(url)
    }

但是当我以编程方式构建电话号码值时,它不起作用:

But when I build the phone number values programmatically it does not work:

//holds phone numbers without special chars
    var tempArray: [String] = []

    //if I can access the unformatted numbers
    if let recips = saveData["recips"] as? [String] {
        //for each number provided
        recips.forEach { (person: String) in
            //remove all non-numerical digits
            //person is now (###) ###-####
            let newPerson = person.digitsOnly()
            //newPerson is ##########
            print(person)
            print("->\(newPerson)")
            //add formatted number to tempArray
            tempArray.append(newPerson)
        }

    }
    //combine all numbers with "," between as a string
    let recipString = tempArray.joinWithSeparator(",")
    //recipString contains ##########,##########,##########...

extension String {

func digitsOnly() -> String{
    let stringArray = self.componentsSeparatedByCharactersInSet(
        NSCharacterSet.decimalDigitCharacterSet().invertedSet)
    let newString = stringArray.joinWithSeparator("")

    return newString
    }
}

然后我在下面的代码中将recipString"变量添加到 NSURL 中:

I then add the "recipString" variable to the NSURL in the below code:

    let messageBody = "test"
    let urlSafeBody = messageBody.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())

    if let urlSafeBody = urlSafeBody, url = NSURL(string: "sms:/open?addresses=\(recipString)&body=\(urlSafeBody)") {
        print("FINAL URL: \(url)")
        WKExtension.sharedExtension().openSystemURL(url)
    }

最终 URL 打印显示正确的字符串,但消息应用程序无法正常打开,并显示快速回复菜单而不是组合消息窗口.它与功能硬编码数字版本完全匹配,但行为不同.

The FINAL URL print shows the correct string, but the messages app does not open properly, and shows quick reply menu instead of composed message window. It matches the functioning hard coded number version exactly, but behaves differently.

完全迷路了,希望有人能帮忙!

Totally lost, hope someone can help!

更新 1以下是两个版本的 URL 的调试打印:

UPDATE 1 Here are the debug prints for both versions of the URL:

手动声明(不是从 recipString 创建,而是在 URL 字符串中明确声明):

Manually declared (not created from recipString but actually declared in the URL string explicitly):

此版本有效

最终网址:sms:/open?addresses=0000000000,1111111111,2222222222,33333333333,4444444444&body=test

FINAL URL: sms:/open?addresses=0000000000,1111111111,2222222222,3333333333,4444444444&body=test

创建的变量(使用 recipString):

Variable created (using recipString):

这个版本没有

最终网址:sms:/open?addresses=0000000000,1111111111,2222222222,33333333333,4444444444&body=test

FINAL URL: sms:/open?addresses=0000000000,1111111111,2222222222,3333333333,4444444444&body=test

我还尝试使用以下 if let 将 url 编码应用于recipString"变量:

I have also tried applying url encoding to the "recipString" variable by using the below if let:

if let urlSafeRecip = recipString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {

        if let urlSafeBody = urlSafeBody, url = NSURL(string: "sms:/open?addresses=\(urlSafeRecip)&body=\(urlSafeBody)") {
            print("FINAL URL: \(url)")
            WKExtension.sharedExtension().openSystemURL(url)
        }
    }

更新 2我通过以下代码测试了数字的硬编码版本是否与 recipString 完全匹配:

UPDATE 2 I tested to see if the hardcode version of numbers matches the recipString exactly via this code:

    let hardCode = "0000000000,1111111111,2222222222,3333333333,4444444444"

    let isEqual = (hardCode == recipString)

    if isEqual {
        print("hardCode matches recipString")
    }
    else {
        print("hardCode does not match recipString")
    }

调试打印:

hardCode 匹配 recipString

hardCode matches recipString

更新 3

我已经确认:

当 URL 由硬编码数字与我从变量创建的数字组成时,检查它们之间的 == 会返回 true.

When a URL is made with hard coded numbers vs. numbers that I make from variables, checking == between them returns true.

在我可以在两个版本的 url 之间进行的每个测试中,它都匹配.

In every test I can do between the two version of the url, it matches.

找到正确答案后的注释:

这种类型的 URL 格式仅适用于 URL 中的多个地址.如果您没有多个地址,您将需要执行以下操作,这是未记录但仍然有效的操作.我是通过在键盘上敲打我的脸几个小时来发现这一点的,所以如果它对你有帮助,那么我就值得点赞 :)

This type of URL formatting will ONLY work with multiple addresses in the URL. If you do not have multiple addresses you will need to do the following, which is undocumented but none-the-less works. I found this by bashing my face on the keyboard for hours, so if it helps you an upvote is deserved :)

按照下面标记的答案,然后在他提到的doItButton()函数中做URL之前使用这种类型的逻辑检查:

follow the answer marked below, and then use this type of logic check before making the URL in the doItButton() function he mentioned:

    func setupAndSendMsg(saveData: NSDictionary) {
    if let urlSafeBody = createBody(saveData) {
        let theNumbers = createNumbers(saveData).componentsSeparatedByString(",")
        print(theNumbers.count-1)
        if theNumbers.count-1 > 0 {
            if let url = NSURL(string: "sms:/open?addresses=\(createNumbers(saveData))&body=\(urlSafeBody)") {
                print(url)
                WKExtension.sharedExtension().openSystemURL(url)
            }
        } else {
            if let url = NSURL(string: "sms:/open?address=\(createNumbers(saveData)),&body=\(urlSafeBody)") {
                print(url)
                WKExtension.sharedExtension().openSystemURL(url)
            }
        }

    }
}

推荐答案

我的猜测是实际的 openSystemUrl 调用不是问题所在.我相信以编程方式构建数字字符串的代码中一定有什么东西.

My guess is that it is not the acctual openSystemUrl call that is the problem. I believe there must be something with the code that is building the number string programmatically.

下面的代码是您发布的所有代码的简化版本.我已经确认它可以在我的 Apple Watch 上运行.它打开带有预填充数字的消息应用程序文章主体.

The code bellow is a simplified version of all the code you have posted. I have confirmed that it is working on my Apple Watch. It opens the Messages app with pre-populated numbers & body text.

再看看你的代码,看看是否有你遗漏的东西.如果你找不到任何东西,只需删除代码并重新编写它,可能会比发现奇怪的问题更快.

Take one more look at your code and see if there is something your missing. If you can't find anything, just delete the code and re-write it, probably will be faster then spotting the weird issue.

再次确认下面的代码按预期工作,所以你应该能够让它工作.(或者只是复制并粘贴我的代码):)

Once again the code bellow is confirmed working as expected, so you should be able to get it to work. (or just copy & paste my code) :)

class InterfaceController: WKInterfaceController {

  @IBAction func doItButton() {
    if let urlSafeBody = createBody() {
      if let url = NSURL(string: "sms:/open?addresses=\(createNumbers())&body=\(urlSafeBody)") {
        print(url)
        WKExtension.sharedExtension().openSystemURL(url)
      }
    }
  }

  private func createBody() -> String? {
    let messageBody = "hello test message"
    return messageBody.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
  }

  private func createNumbers() -> String {
    let numbers = ["(111) 222-3333", "(444) 555-6666"]
    var tempArray: [String] = []
    numbers.forEach { (number: String) in
      tempArray.append(number.digitsOnly())
    }

    return tempArray.joinWithSeparator(",")
  }      
}

extension String {
  func digitsOnly() -> String{
    let stringArray = self.componentsSeparatedByCharactersInSet(
      NSCharacterSet.decimalDigitCharacterSet().invertedSet)
    let newString = stringArray.joinWithSeparator("")

    return newString
  }
}

<小时>

如上所述,出于评论中已经提到的原因,我建议您不要将未记录的 Apple 功能用于您计划放在 App Store 上的任何内容.


With above said I would recommend against using undocumented Apple features for anything you plan on putting on the App Store for the reasons already mentioned in comments.

这篇关于AppleWatch 消息 URL 可以硬编码,但不能使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆