【问题标题】:Bug Xcode 7.3 with iOS 9.2 dataWithContentsOfURL带有 iOS 9.2 dataWithContentsOfURL 的错误 Xcode 7.3
【发布时间】:2016-07-04 03:05:02
【问题描述】:

我有一个超级简单的代码,可以从网上下载一张图片。它在 iOS 8 中运行良好,但现在我在带有 iOS 9 的 Xcode 7.3 中不断收到此错误。这是一个错误吗?

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
NSString* documentsPath = [paths objectAtIndex:0];

NSError *error;
NSString *data2URL = @"http://cdn.minecraftpocket-servers.com/images/flags/Brazil.png";
NSURL *url = [NSURL URLWithString:data2URL];
NSString *imgFileNameStr = [data2URL lastPathComponent];

NSData *data2 = [NSData dataWithContentsOfURL:url options: NSDataReadingUncached error: &error];

if (error)
    NSLog(@"Download error: %@",error);

//check
if (data2 == NULL)
{
    NSLog(@"DATA IS NULL");
}
else
{
    NSLog(@"DATA IS NOT NULL");
}

//saving file
NSString* fullPathToFile2 = [documentsPath stringByAppendingPathComponent:imgFileNameStr];
BOOL success = [data2 writeToFile:fullPathToFile2 atomically:NO];
NSLog(@"Success = %d ...", success);

错误:

2016-07-03 23:00:36.963 014-test-proj[15404:419151] Download error: Error Domain=NSCocoaErrorDomain Code=256 "The file “Brazil.png” couldn’t be opened." UserInfo={NSURL=http://cdn.minecraftpocket-servers.com/images/flags/Brazil.png}
2016-07-03 23:00:36.963 014-test-proj[15404:419151] DATA IS NULL
2016-07-03 23:00:36.964 014-test-proj[15404:419151] Success = 0 ...

我已经检查并确保了我的 plist 文件的应用程序安全性。

有人遇到了同样的问题HERE。我错过了什么?

更新: 如果我使用这个链接,代码就可以工作......

NSString *data2URL =@"https://upload.wikimedia.org/wikipedia/commons/1/1e/Large_Siamese_cat_tosses_a_mouse.jpg";

我不明白。为什么它会与另一个有问题。

【问题讨论】:

    标签: ios objective-c xcode


    【解决方案1】:

    您不应该调用[NSData dataWithContentsOfURL:url] 从远程 URL(即互联网上的某个地方)下载数据。你的代码很糟糕,而且你正在做同步网络,这总是错误的。现在你被运行时阻止了,这是正确的。要下载数据,请下载。使用 NSURLSession。这就是它的用途。

    【讨论】:

    • 不,没有效果。我将代码更改为 NSURLSession,它会下载文件但无法打开。还有其他事情发生。自己试试吧。 PS。查看更新的链接
    • 我注意到有一个重定向。这可能与它有关。
    【解决方案2】:

    不同之处在于使用安全 URL 的变化。 Apple 引入了 App Transport Security (ATS),现在您的应用程序 plist 中有一个设置,您必须启用它才能从非 http so 形式的 URL 加载。

    将以下内容添加到您的 Info.plist 以禁用 ATS

    <key>NSAppTransportSecurity</key>  
         <dict>  
              <key>NSAllowsArbitraryLoads</key><true/>  
         </dict>  
    

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 2018-05-27
      • 2018-05-05
      • 2016-07-22
      • 2018-08-02
      • 1970-01-01
      相关资源
      最近更新 更多