2017-11-21 2 views
3

~ 1300 이미지를 다운로드 중입니다. 그것들은 총 이미지 크기가 약 500KB 정도되는 작은 이미지입니다. 그러나 다운로드 userDefault에 넣어 후에, 나는 다음과 같은 오류가 발생합니다 :Swift를 사용하여 열린 파일을 어떻게 닫습니까?

libsystem_network.dylib을 : nw_route_get_ifindex :: 소켓 (PF_ROUTE, SOCK_RAW, PF_ROUTE가) 실패 : [24] 열려있는 파일이 너무 많습니다

아마 다운로드 한 png 이미지가 닫히지 않고있는 것입니다.

나는 이미 확장 캐시 크기를 아래로 :

func storeImages(){ 
     for i in stride(from: 0, to: Cur.count, by: 1) { 
      // Saving into userDefault 
      saveIconsToDefault(row: i) 
     } 
    } 

내가 그들 모두 후 오류가 userDefault에 추가되는 :

// Configuring max network request cache size 
    let memoryCapacity = 30 * 1024 * 1024 // 30MB 
    let diskCapacity = 30 * 1024 * 1024 // 30MB 
    let urlCache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "myDiscPath") 
    URLCache.shared = urlCache 

그리고 이것은 내가 이미지를 저장할 수있어 접근 방식입니다. 그래서, 나는 그들이 거기 있다는 것을 알고있다.

EDIT :

함수 :

func getImageFromWeb(_ urlString: String, closure: @escaping (UIImage?) ->()) { 
    guard let url = URL(string: urlString) else { 
     return closure(nil) 
    } 
    let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in 
     guard error == nil else { 
      print("error: \(String(describing: error))") 
      return closure(nil) 
     } 
     guard response != nil else { 
      print("no response") 
      return closure(nil) 
     } 
     guard data != nil else { 
      print("no data") 
      return closure(nil) 
     } 
     DispatchQueue.main.async { 
      closure(UIImage(data: data!)) 
     } 
    }; task.resume() 
} 

func getIcon (id: String, completion: @escaping (UIImage) -> Void) { 
    var icon = UIImage() 

    let imageUrl = "https://files/static/img/\(id).png" 

     getImageFromWeb(imageUrl) { (image) in 
      if verifyUrl(urlString: imageUrl) == true { 
       if let image = image { 
        icon = image 
        completion(icon) 
       } 
      } else { 
       if let image = UIImage(named: "no_image_icon") { 
        icon = image 
        completion(icon) 
       } 
      } 
     } 
} 

USAGE :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "CurrencyCell", for: indexPath) as? CurrencyCell else { return UITableViewCell() } 

    if currencies.count > 0 { 
     let noVal = currencies[indexPath.row].rank ?? "N/A" 
     let nameVal = currencies[indexPath.row].name ?? "N/A" 
     let priceVal = currencies[indexPath.row].price_usd ?? "N/A" 

     getIcon(id: currencies[indexPath.row].id!, completion: { (retImg) in 
      cell.configureCell(no: noVal, name: nameVal, price: priceVal, img: retImg) 
     }) 
    } 
    return cell 
} 
+2

'UIImage's를'UserDefaults'에 저장하지 마십시오. 절대로. 특히 1300 이미지가 아닙니다. – the4kman

+0

입력 해 주셔서 감사합니다. 그러나, 당신이 또한 그 (것)들을 어디에 두는 지 지적하는 경우에 좋지 않을 ㅂ니까? – sc13

+0

https://stackoverflow.com/questions/6238139/ios-download-and-save-image-inside-app try this this –

답변

1

URLSession(configuration: .default) 구문은 각각의 요청에 대한 새로운 URLSession를 생성한다. 하나의 URLSession (일부 속성에 저장)을 만든 다음 모든 요청에 ​​대해 다시 사용하십시오. 당신이 정말로 URLSession의 사용자 정의 구성을 수행하지 않는 경우 또는, 단지 URLSession.shared를 사용

let task = URLSession.shared.dataTask(with: url) { data, response, error in 
    ... 
} 
task.resume() 

당신은 UserDefaults 1300 개 이미지를 저장하고 있다는 언급. 이 유형의 데이터를 저장할 정확한 위치가 아니며 해당 양의 파일도 저장할 수 없습니다. File System Programming Guide: The Library Directory Stores App-Specific Files에 설명 된대로 "캐시"폴더를 사용하는 것이 좋습니다.

let cacheURL = try! FileManager.default 
    .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 
    .appendingPathComponent("images") 

// create your subdirectory before you try to save files into it 
try? FileManager.default.createDirectory(at: cacheURL, withIntermediateDirectories: true) 

"Documents"폴더에도 저장하지 마십시오. 자세한 내용은 iOS Storage Best Practices을 참조하십시오.

관련 문제