2017-09-21 35 views
0

IOS開発が初めてで、URLから画像を読み込もうとしていますが、迅速なバージョン間にいくつかの変更があることを理解しています。私は画像データ= nilのを取得し、私はなぜ..URL画像を読み込む

private func fetchImage() 
{ 
    let url = URL(fileURLWithPath: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png") 
    if let imageData = NSData(contentsOf: url as URL){ 
      image = UIImage(data: imageData as Data) 
    } 
    } 

答えて

0

確認してください:

private func fetchImage() { 
    let url = URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png")! 
    let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in 
     if error != nil { 
      print("Error Occurred: \(String(describing: error))") 
     } 
     else { 
      if let imageData = data { 
       let image = UIImage(data: imageData) 
      } else { 
       print("Image file is currupted") 
      } 
     } 
    } 
    task.resume() 
} 
+0

URLRequestの無意味な使用。あなたは単にURLを渡すことができます。 –

0

あなたはURLの間違った初期化子を使用しているかわからない何らかの理由 。これはファイルシステムのURL用であり、ネットワークURL用ではありません。 Data(contentsOf:)は同期メソッドであり、したがってのみ、インターネットからローカルファイルではなく、ファイルを取得するために使用されなければならないので、

private func fetchImage(){ 
    if let url = URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png"), let imageData = try? Data(contentsOf: url){ 
     image = UIImage(data: imageData) 
    } 
} 

しかし、あなたは完全にあなたの関数を書き換える必要があります。これは、あなたの関数の作業バージョンです。

func fetchImage(from url:URL, completion: @escaping (UIImage?)->Void){ 
    URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in 
     guard error == nil, let data = data else { 
      completion(nil);return 
     } 
     completion(UIImage(data: data)) 
    }).resume() 
} 

fetchImage(from: URL(string: "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2017/09/blog_1280x720.png")!, completion: {image in 
    if let image = image { 
     //use the image 
    } else { 
     //an error occured and the image couldn't be retrieved 
    } 
}) 
+0

をユーザーが、彼はまた、情報のplist NSAppTransportSecurityで任意の負荷を許可するか、URLがhttpsである –

+0

例外ドメインを追加する必要が間違ったURLの初期化子を使用しているという事実のほかに私はそれが必要となる理由は見当たりません。 –

関連する問題