我无法完全删除图片和所有"元数据"来自NSMutableAttributedString中的NSAttachMent。为了对我的场景给出高级别的解释 - 用户可以将图像或文本上传到社交媒体源。我使用UITextView作为文本和图像的输入和显示。所以我的想法是,如果用户想要插入消息和图像(反之亦然),我使用下面的代码:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
imagePicker?.dismissViewControllerAnimated(true, completion: nil)
let mutableAttrString = NSMutableAttributedString()
let attachment = NSTextAttachment()
var width : CGFloat?
var height : CGFloat?
let size = CGSizeMake(width!, height!)
let imgToDisplay = scaleImageWithoutChangingAspect(image!, toSize: size)
attachment.image = imgToDisplay
mutableAttrString.appendAttributedString(format.prepAtrributedString(textToStore + "\n", f: UIFont(name: fontRegular, size: 20)!, Color: UIColor.blackColor()))
let attString = NSAttributedString(attachment: attachment)
mutableAttrString.appendAttributedString(attString)
//add this attributed string to the current position.
self.TextMessage.textStorage.insertAttributedString(mutableAttrString, atIndex: self.TextMessage.selectedRange.location)
self.TextMessage.attributedText = mutableAttrString
self.TextMessage.invalidateIntrinsicContentSize()
self.TextMessage.updateConstraintsIfNeeded()
self.TextMessage.layoutIfNeeded()
}
以下是我用来尝试从属性文本中删除图片的代码,但是在删除后我看到了一个unicode字符\u{ef}
:
let s = self.TextMessage.text
self.TextMessage.resignFirstResponder()
print(s)
let mutAttrString = NSMutableAttributedString(attributedString: self.TextMessage.attributedText)
let range = NSMakeRange(0, mutAttrString.length)
mutAttrString.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions.Reverse) { (OBJS, Range, B) -> Void in
for s in OBJS {
if s.0 == "NSAttachment" {
mutAttrString.removeAttribute(s.0, range: Range)
}
}
}
mutAttrString.endEditing()
var insertMessageData = mutAttrString.string
let db = SwiftDatabase()
var ImgData : NSData?
if let i = selectedImage {
ImgData = UIImageJPEGRepresentation(i, 0.5)
}
///Insert text and upload image to database.
let tup = db.insertShowMessage(insertMessageData, data: ImgData,delegate: self)
key_id = tup.KeyId
query = tup.Query
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
我也尝试将文本转换为ASCII,但我仍然看到" Meta数据" NSTextAttachMent。我没有使用unicode字符,而是看到了#34;?。#34;
我非常感谢任何帮助。谢谢!