gpt4 book ai didi

ios - 既然我们有 [NSData dataWithContentsOfURL :], 为什么我们要使用 [NSURLConnection sendSynchronousRequest :returningResponse:error:]?

转载 作者:行者123 更新时间:2023-11-28 22:04:21 24 4
gpt4 key购买 nike

我们可以通过下面的代码轻松获取简单的网页内容:

+ (NSString *)getContentWithURL:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
if(!data) {
return @"";
} else {
return [NSString stringWithUTF8String:[data bytes]];
}
}

但是有人告诉我使用 NSURLConnection?

最佳答案

两者是不同的东西:

dataWithContentsOfURL:

This method is ideal for converting data:// URLs to NSData objects, and can also be used for reading short files synchronously. If you need to read potentially large files, use inputStreamWithURL: to open a stream, then read the file a piece at a time.

Important: Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

sendSynchronousRequest:returningResponse:error:

A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

Important: Because this call can potentially take several minutes to fail (particularly when using a cellular network in iOS), you should never call this function from the main thread of a GUI application.

关于ios - 既然我们有 [NSData dataWithContentsOfURL :], 为什么我们要使用 [NSURLConnection sendSynchronousRequest :returningResponse:error:]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24382723/

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