我的应用程序有一个操作按钮来拉出 UIActivityViewController。在我的测试设备 5S 上,它一切正常,包括发短信。但是,在我的 5C 测试设备上,它在尝试发送消息时崩溃。我的代码是否有问题,可以使它与某些手机一起发送消息,而不是其他手机?
下面列出的代码有一些注意事项。首先,有时要发送的文本会超过 140 个字符,所以我先检查字符串的长度。如果超过 140 个字符,它会剪掉中间部分,在末尾添加 ...,并保持在 140 个字符。然后,在操作中,如果超过 140 个字符,它只为 Twitter 和 Message 发送已编辑的字符串,但为所有其他字符发送常规字符串,如果 140 个字符或以下,则发送常规字符串。
-(void)sendit {
NSString *string = label1.text;
if ([string length] > 140) {
int maxChars = 140;
int charsOver = [string length] - maxChars;
NSString *replacementString = @"...";
charsOver += [replacementString length]; //account for adding "..."
NSArray *components = [string componentsSeparatedByString:@" - "];
NSMutableString *stringToTrim = [NSMutableString string];
int numberOfComponents = [components count];
for (int i = 0; i < numberOfComponents - 1; i++) {
NSString *component = [components objectAtIndex:i];
if (i < numberOfComponents - 2) {
[stringToTrim appendFormat:@"%@ - ", component];
}
else {
[stringToTrim appendString:component];
}
}
NSString *trimmedString = [stringToTrim substringToIndex:[stringToTrim length] - charsOver];
self.finalString = [NSString stringWithFormat:@"%@%@%@", [trimmedString stringByAppendingString:replacementString], @" - ", [components objectAtIndex:numberOfComponents - 1]];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[self] applicationActivities:nil];
activityVC.excludedActivityTypes = @[ UIActivityTypePostToWeibo,
UIActivityTypeAssignToContact,
UIActivityTypePrint,
UIActivityTypeAirDrop
];
[self presentViewController:activityVC animated:YES completion:nil];
}
else {
NSArray *activityItems = @[label1.text];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityVC.excludedActivityTypes = @[ UIActivityTypePostToWeibo,
UIActivityTypeAssignToContact,
UIActivityTypePrint,
UIActivityTypeAirDrop
];
[self presentViewController:activityVC animated:YES completion:nil];
}
}
- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
if ([activityType isEqualToString:UIActivityTypeMail]) {
NSLog(@"TEST");
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypePostToTwitter]){
NSString *string = label1.text;
if ([string length] > 140) {
return self.finalString;
}
else {
return label1.text;
}
}
if ([activityType isEqualToString:UIActivityTypePostToFacebook]){
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypeCopyToPasteboard]){
return label1.text;
}
if ([activityType isEqualToString:UIActivityTypeMessage]){
NSString *string = label1.text;
if ([string length] > 140) {
return self.finalString;
}
else {
return label1.text;
}
}
return nil;
}