0

This is a follow-up from a previous post here.

I am now trying to access the array and use it to populate my collectionView. When I try the following code, my imageData comes back as nil and I get a crash, even though the imageURL correctly shows as a filepath.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let usD = UserDefaults.standard
    let array = usD.stringArray(forKey: "WeatherArray") ?? []

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell

    let myString = array[indexPath.row]
    let imageUrl = URL(string: myString)!
    let imageData = try? Data(contentsOf: imageUrl)
    let image = UIImage(data: imageData!)
    cell.myImageView.image = image

Here is an example of my URL(string: myString) below:

file:///private/var/mobile/Containers/Data/Application/6DD4ED20-F1BB-46DB-8A8C-35C3CFB2B2C6/tmp/01431A0E-F7C2-4A60-B1C6-5C9508C75863.jpeg

Also, inspecting imageUrl shows this error:

Printing description of imageUrl: expression produced error: error: /var/folders/np/4m9vk2yd0bzbf74lxrnffccr0000gn/T/expr9-6d45ad..swift:1:65: error: use of undeclared type 'Foundation' Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Foundation.URL>(bitPattern: 0x1054f86a0)!.pointee)

8
  • Your url string points to a temporary file tmp. You can't save a reference to a temporary file. If you are willing to load that file later you need to copy/move that file to a directory inside your app sandbox (documents directory) Commented Jan 8, 2018 at 1:59
  • Btw you are not saving the URL path you are saving its absoluteString which it is not the same. It includes the url scheme which forces you to use URL(string:) initializer instead of URL(fileURLWithPath:) Commented Jan 8, 2018 at 2:06
  • What you need to do is to copy/move your image inside imagePicker didFinishPickingMediaWithInfo method before it finishes. Your temporary image it is usually removed when that method finishes executing. Commented Jan 8, 2018 at 2:08
  • check this post stackoverflow.com/questions/48133840/… Commented Jan 8, 2018 at 2:09
  • 1
    Yes! This helped immensely. Thank you so much @LeoDabus For those looking at this, I also used the answer from here to help round out my code. Commented Jan 8, 2018 at 2:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.