UIPasteboard:NSString拒绝复制到剪贴板

问题描述 投票:0回答:2

我有以下代码使用bit.ly API缩短URL。

NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", login, key, self.link.text]] encoding:NSUTF8StringEncoding error:nil];

我也有以下代码将缩短的URL复制到粘贴板:

UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = shortenedURL;

但是,这不起作用。在输出日志中,将显示以下内容:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIPasteboard setString:]: Argument is not an object of type NSString [(null)]'

因此,如果参数不是对象,那是什么?我尝试假设它是一个URL:

UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.URL = shortenedURL;

产生相同类型的错误,只说参数不是NSURL对象,而不是先前的错误,说参数不是NSString对象。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIPasteboard setURL:]: Argument is not an object of type NSURL [(null)]'

任何人都知道该怎么办?

ios objective-c uipasteboard
2个回答
1
投票
NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", login, key, self.link.text]] encoding:NSUTF8StringEncoding error:nil];  

为零,因此忽略该错误不是一个好主意。代替的是,执行

NSError *loadingError = nil
NSString *shortenedURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.bit.ly/v3/shorten?login=%@&apikey=%@&longUrl=%@&format=txt", login, key, self.link.text]] encoding:NSUTF8StringEncoding error:&loadingError]; 
if (!shortenURL) {
    NSLog(@"Error loading: %@", loadingError);
    return;
} else {
    NSLog(@"Success loading: %@", shortenedURL); 
}

您应该得到“错误加载:错误消息在这里”,并调试发生的确切问题。


0
投票

[不幸的是,string对象上的UIPasteboard属性实际上不是字符串,而是具有您所关心的给定类型的Objective-C数组的吸气剂和吸气剂的接口。

Swift提供了可选的选项,但是不幸的是UIPasteboard是幕后的Objective-C,实际上并不能很好地支持可选的选项。这是其中一种情况。

如果将nil(空)分配给string属性,则执行会将空值包装在方括号中,作为数组[(null)],然后尝试将其添加到类型为[NSURL]的空数组中,因为[(null)][NSURL]的类型不匹配,您将得到:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIPasteboard setURL:]: Argument is not an object of type NSURL [(null)]'

😤

© www.soinside.com 2019 - 2024. All rights reserved.