2017-07-05 5 views
1

Je télécharge l'image du serveur et quand l'image est téléchargée je dois enregistrer cette image dans la coredata avec l'identification. Voici le codeComment passer à URLSession.shared.dataTask appelé dans une boucle?

for actionDict:JSON in actionData 
    { 
    if(actionDict["ProtocolImage"].stringValue.isValidURL()) 
     { 
      URLSession.shared.sessionDescription = "\(actionDict["Id"].intValue)" 
      URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in 
       if data != nil{ 
        let image = UIImage(data: data!) 
        if image != nil{      
         ProtocolActionModel.updateValueWhere(id: Int64(URLSession.shared.sessionDescription!)!, key: "protocolImage", value:(UIImagePNGRepresentation(image!)! as NSData)) 
        } 
       } 
      }).resume() 
     } 
    } 

(actionDict["Id"].intValue est id associé à l'image que je veux enregistrer dans CoreData avec l'image, mais quand je l'enregistrer est toujours à la dernière id élément de boucle.

actionData est

{ 
    data =  (
       { 
      CheckDesc = vcnhfgb; 
      CheckName = hjnhfnmjh; 
      CheckedImage =    (
      ); 
      CreatedDate = "/Date(1487201399293)/"; 
      Id = 3; 
      IsChecked = 0; 
      ProtocolId = 4; 
      ProtocolImage = "http://example.com/ApplicationImages/522cb086-0b0d-4ad9-b5ae-79f6f9a9fbf2.jpg"; 
      Sorting = "<null>"; 
     }, 
       { 
      CheckDesc = bfghrthbn; 
      CheckName = ddfgb; 
      CheckedImage =    (
      ); 
      CreatedDate = "/Date(1499167861457)/"; 
      Id = 71; 
      IsChecked = 0; 
      ProtocolId = 4; 
      ProtocolImage = "http://example.com/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png"; 
      Sorting = 41; 
     }, 
       { 
      CheckDesc = bnvbncyh; 
      CheckName = nbnyhjhg; 
      CheckedImage =    (
      ); 
      CreatedDate = "/Date(1499167894280)/"; 
      Id = 72; 
      IsChecked = 0; 
      ProtocolId = 4; 
      ProtocolImage = "http://example.com/ApplicationImages/e4311494-27ad-4d12-958b-68e0c705a94d.png"; 
      Sorting = 42; 
     }, 
       { 
      CheckDesc = hjbnvbytuu; 
      CheckName = nmnmhjgh; 
      CheckedImage =    (
      ); 
      CreatedDate = "/Date(1499167918147)/"; 
      Id = 73; 
      IsChecked = 0; 
      ProtocolId = 4; 
      ProtocolImage = "http://example.com/ApplicationImages/15ac0300-8877-4503-8c6d-957b5248e829.png"; 
      Sorting = 43; 
     }, 
       { 
      CheckDesc = ""; 
      CheckName = tyres; 
      CheckedImage =    (
      ); 
      CreatedDate = "/Date(1499172466890)/"; 
      Id = 74; 
      IsChecked = 0; 
      ProtocolId = 4; 
      ProtocolImage = "<null>"; 
      Sorting = 44; 
     } 
    ); 
    message = success; 
    status = 1; 
} 

Reponse

<NSHTTPURLResponse: 0x600000634720> { URL: http://example/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png } { status code: 200, headers { 
    "Accept-Ranges" = bytes; 
    "Content-Length" = 254882; 
    "Content-Type" = "image/png"; 
    Date = "Wed, 05 Jul 2017 05:31:46 GMT"; 
    Etag = "\"e09aa43b9f4d21:0\""; 
    "Last-Modified" = "Tue, 04 Jul 2017 11:31:01 GMT"; 
    Server = "Microsoft-IIS/7.5"; 
    "X-Powered-By" = "ASP.NET"; 
    "X-Powered-By-Plesk" = PleskWin; 
} } 

S'il vous plaît fournir une solution qui résoudra mon problème.

+0

'(actionDict [ « Id »]. IntValue' est la même pour toutes les images? –

+0

@DharmeshKheni pas tous différents –

+0

raison pourrait être votre boucle pour mettre fin à la course à pied avant que les données sont sauvegardées dans la base. Et par conséquent, Débogage et vérification – Gihan

Répondre

1

Je n'ai pas compilé cet espoir que vous pouvez avoir l'idée. En supposant que l'URL est unique à l'ID, vous pouvez la conserver en tant que clé et y accéder dans le gestionnaire d'achèvement.

//: Playground - noun: a place where people can play 

import UIKit 

var str = "Hello, playground" 

var keyDictionary = [String: Int]() 
for actionDict:JSON in actionData 
{ 
    if(actionDict["ProtocolImage"].stringValue.isValidURL()) 
    { 
     keyDictionary[actionDict["ProtocolImage"].stringValue] = actionDict["Id"].intValue 
     URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in 
      if data != nil{ 
       let image = UIImage(data: data!) 
       if image != nil{ 
        realValue = keyDictionary[response.URL]; 
        ProtocolActionModel.updateValueWhere(id: Int64(realvalue!)!, key: "protocolImage", value:(UIImagePNGRepresentation(image!)! as NSData)) 
       } 
      } 
     }).resume() 
    } 
} 
+0

Merci résolu mon problème en faisant peu de changements. –

+1

Heureux d'être une aide! à votre santé ! – Gihan

1

Au lieu de URLSession.shared.dataTask j'utilise NSData(contentsOf: url as URL) pour télécharger des images depuis l'URL.

pour par exemple:

Je fais juste avec des données statiques remplacer par dynamique

var resultArray = [Dictionary<String,Any>]() 
    var resultDict1 = Dictionary<String,Any>() 
    resultDict1["Id"] = 3 
    resultDict1["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/asd.png" 

    var resultDict2 = Dictionary<String,Any>() 
    resultDict2["Id"] = 7 
    resultDict2["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png" 

    var resultDict3 = Dictionary<String,Any>() 
    resultDict3["Id"] = 9 
    resultDict3["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png" 

    resultArray.append(contentsOf: [resultDict1,resultDict2,resultDict3]) 

    for actionDict in resultArray { 
     //here check your URL is valid one 
     if let url = URL(string: (actionDict["ProtocolImage"] as? String ?? "".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!) { 

       DispatchQueue.global(qos: .background).async { 
        // Background Thread 
        let imageData = NSData(contentsOf: url as URL) 
        if let data = imageData { 
         if let image = UIImage(data: data as Data) { 
          print(actionDict["Id"] as? Int ?? 0) 
          print(actionDict["ProtocolImage"] as? String ?? "") 

          //here itself you can able to save image to coredata 
          DispatchQueue.main.async { 
           //update UI part if requires 
          } 
         } 
        } 
       } 
      } 
     } 

La sortie:

ici, vous obtiendrez id correct pour l'image.

7 
https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png 
9 
https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png 
3 
https://alperkayabasi.files.wordpress.com/2014/10/asd.png 
+0

Pour votre réponse, mais Gihan réponse a moins de changements à ce que je dois faire dans mon code, donc je choisis cela comme correct –

+0

@VarunNaharia pas de soucis je m juste poster pour d'autres façons ... heureux d'aider –

+0

Quoi qu'il en soit merci mon pote –