如果与其他代码放在 IB 操作中,程序将跳过用于下载 txt 文件的 NSURLRequest
Program skips NSURLRequest used to download txt file, if placed in IB action with other code
我在 objective -c 中使用 NSURL 请求来下载网页并将其放入文本文件中。这类似于 UNIX 中使用的 curl 函数。
代码如下:
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"data.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://ca.finance.yahoo.com/q?s=JNJ"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
我发现如果我在链接到测试按钮的它自己的 IB 操作(没有其他代码)中执行代码,它就没有错误。
然而,在主要的 IB 操作中,程序编译器似乎跳过了代码而不执行它(观察到缺少下载文件)。我将不胜感激有关此错误的可能来源的反馈。
谢谢
您必须创建一个 NSOperationQueue
实例:
[NSURLConnection sendAsynchronousRequest:request [NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
我在 objective -c 中使用 NSURL 请求来下载网页并将其放入文本文件中。这类似于 UNIX 中使用的 curl 函数。
代码如下:
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"data.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://ca.finance.yahoo.com/q?s=JNJ"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
我发现如果我在链接到测试按钮的它自己的 IB 操作(没有其他代码)中执行代码,它就没有错误。
然而,在主要的 IB 操作中,程序编译器似乎跳过了代码而不执行它(观察到缺少下载文件)。我将不胜感激有关此错误的可能来源的反馈。 谢谢
您必须创建一个 NSOperationQueue
实例:
[NSURLConnection sendAsynchronousRequest:request [NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {