NSData contentsOfUrl returns nil

前端 未结 2 940
野的像风
野的像风 2021-01-05 15:25

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         


        
相关标签:
2条回答
  • 2021-01-05 15:45

    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>
    
    0 讨论(0)
  • 2021-01-05 15:49

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题