gpt4 book ai didi

ios - 如何将特定字符串替换为 NSTextAttachment 以显示图像

转载 作者:行者123 更新时间:2023-11-30 12:43:13 25 4
gpt4 key购买 nike

我会得到很多消息字符串

像这些:

1.hello {{http://i.imgur.com/f1cqT3ut.jpg}} 世界 {{http://i.imgur.com/f1cqT3ut.jpg}}

2.hi {{http://i.imgur.com/iVx9iqjt.jpg}} {{http://i.imgur.com/iVx9iqjt.jpg}} 如何{{http://i.imgur.com/ZpXgxiXt.jpg}} 是 {{http://i.imgur.com/rcdHObKt.jpg}} 你是 {{http://i.imgur.com/yX5dHdet.jpg}} 吗? {{http://i.imgur.com/2iZSBKGt.jpg}}

我想处理这些消息

像这些:

1. message handled 1

2. message handled 2

现在我只知道可以使用 NSMutableAttributedString 显示所有已处理的消息并使用 NSTextAttachment 显示 url 图像。

但我不知道如何替换和处理这些消息。

请帮助我。

谢谢。

最佳答案

如果您可以假设每个字符串都是这样设置的,其中单词和 URL 用空格分隔 - 并且 URL 都包含在两组大括号内,那么您可以创建一个方法来获取字符串并将其分割成一个子字符串数组(用空格分隔),然后您可以检查是否有以“{{”开头的子字符串来知道它是一个 URL。我刚刚写了这样的东西,它将返回一个元组数组,其中每个元组都是一个整数(与子字符串数组中 URL 的索引相关),以及一个表示从大括号中删除的 URL 的字符串。

func split(_ s: String) -> [(Int, String)] {

// Separate the original string into an array of substrings separated by a space
let separated = s.components(separatedBy: " ")
// Filter the separated array to find the URLs that start with {{
var urls = separated.filter{ $0.hasPrefix("{{") }
// Map the urls array to get an array of ints correlating to their respective indices from the separated array
let indicies = urls.map { separated.index(of: $0) }
// create an empty array of Int and String tuples
var tuples: [(Int, String)] = []

// Loop through the url array
for i in 0 ..< urls .count {

// Remove the left side (open) curly brackets
urls[i] = urls[i].replacingOccurrences(of: "{{", with: "")
// Remove the right side (close) curly brackets
urls[i] = urls[i].replacingOccurrences(of: "}}", with: "")

// Append the tuple with the url's index from the separated array and it's actual url value as a string
tuples.append((indicies[i]!, urls [i]))
}
return tuples
}

然后,您可以使用它从网址中分割单词,然后获取图像(这取决于您 - 可能使用 Alamofire 甚至只是 NSURLSession),然后因为您有了它们的子字符串数组中的原始索引 - 您仍然知道它们的顺序。因此,一旦异步请求返回,就根据原始顺序重新排列它们,然后使用夹在 之间的 UILabels UIImageViews(或反之亦然)以您尝试的方式显示内容。

关于ios - 如何将特定字符串替换为 NSTextAttachment 以显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com