Objective c 使用swift的queryURL在使用目标C时不起作用

Objective c 使用swift的queryURL在使用目标C时不起作用,objective-c,swift,url,nsstring,Objective C,Swift,Url,Nsstring,我需要和斯威夫特一起工作。我是swift的新手,我曾经用objective C做过这项工作。它在目标C中正确工作。 这是我的objective C项目的代码,它工作正常 NSString* queryURL; queryURL = [NSString stringWithFormat:@"https://google.com]; NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet]; NSString *re

我需要和斯威夫特一起工作。我是swift的新手,我曾经用objective C做过这项工作。它在目标C中正确工作。 这是我的objective C项目的代码,它工作正常

NSString* queryURL;

queryURL = [NSString stringWithFormat:@"https://google.com];


NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];

NSString *result = [queryURL stringByAddingPercentEncodingWithAllowedCharacters:set];

NSURL *googleURL = [NSURL URLWithString:result];

NSError *error;

NSString *googlePage = [NSString stringWithContentsOfURL:googleURL

                                                encoding:NSASCIIStringEncoding

                                                   error:&error];


   NSLog(@"Back%@", googlePage);
正如我所说,它工作得很好。现在我将其更改为以下swift代码

   if let url = URL(string: "https://google.com") {

    do {

        let contents = try String(contentsOf: url)

        print(contents)

    } catch {

        // contents could not be loaded

    }

} else {

    // the URL was bad!

}

但是它遇到了一个错误
无法加载内容
如果有人能帮助我,我真的很感激

您省略了swift中的编码(该参数在swift中是可选的,但在objc中是必需的):
let contents=try String(contentsOf:url,encoding:ascii)

swift在清理各种标准库类型的职责方面更加严格。
NSString
负责从URL加载自己是不明智的。想象一下,如果
String
负责从任何可以加载字符串的地方加载自己,会发生什么情况。数据库、文件系统、YAML/JSON/CSV/XML等。它将大量膨胀。相反,在Swift中,您将使用
URLSession
。这也解决了第二个问题:这个ObjC代码是同步的,使整个程序等待网络调用。这绝对不是一个好的使用体验。@Alexander非常感谢,似乎是非常有用的信息。你能回答这个问题吗?如果可能的话,请告诉我你的建议是什么?谢谢你看