NSData contentsOfUrl returns nil

こ雲淡風輕ζ 提交于 2019-11-30 05:05:15

问题


I found several similar questions on StackOverflow but none of them solve my problem.

I am trying to get a image from a url. Here's how I do it:

let url = NSURL(string: "http://pic3.zhimg.com/8161ba9638273e0fb1a0201789d22d8e_m.jpg")
let data = NSData(contentsOfURL: url!)
let image = UIImage(data: data!)

But I got an error telling me that data is nil.

How can I solve this? Thanks.

UPDATE

Here's some screenshots of the error:


回答1:


This is probably a result of Apple's new app transport security denying a non-HTTPS request. To work around this you need to modify your app's Info.plist file. You can either define an exception for that particular domain

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>pic3.zhimg.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

or disable ATS altogether

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



回答2:


I think you should, before all, create a resilient code.

if let url = NSURL(string: "http://pic3.zhimg.com/8161ba9638273e0fb1a0201789d22d8e_m.jpg")
{ 
    if let data = NSData(contentsOfURL: url) 
    {
        if let image = UIImage(data: data) 
        {
            //Do something
        }
    }
}


来源:https://stackoverflow.com/questions/32567710/nsdata-contentsofurl-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!