简体   繁体   English

如何传递给循环调用的URLSession.shared.dataTask?

[英]How to pass to URLSession.shared.dataTask called in a loop?

I am downloading image from server and when image is downloaded I have to save that image in coredata with id. 我正在从服务器下载图像,下载图像时,我必须将该图像保存在具有ID的coredata中。 Here is the code 这是代码

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 is id associated with image that I want to save in coredata with image but when I save it is always set to last item id of for loop. (actionDict["Id"].intValue是与我要保存在图像中的核心数据中的图像相关联的ID,但是在保存时,它始终设置为for循环的最后一个ID。

actionData is actionData

{
    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;
} }

Please provide any solution that will solve my problem. 请提供任何可以解决我的问题的解决方案。

I have not compiled this hope you can get the idea. 我还没有汇编这个希望您能理解的想法。 Assuming URL is unique to ID you can keep it as a key and access it inside the completion handler. 假设URL是ID唯一的,则可以将其保留为密钥并在完成处理程序中访问它。

//: 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()
    }
}

Instead of URLSession.shared.dataTask i am using NSData(contentsOf: url as URL) to download images from URL. 我不是使用URLSession.shared.dataTask而是使用NSData(contentsOf: url as URL)从URL下载图像。

for eg: 例如:

I am just doing with static data replace it with dynamic 我只是在处理静态数据,而是将其替换为动态数据

   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
                            }
                        }
                    }
                }
            }
        }

The output : 输出 :

here you will get correct id for image. 在这里,您将获得正确的图像ID。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在URLSession.shared.dataTask之后调用performSegue - Call performSegue after URLSession.shared.dataTask URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask 使用URLSession.shared.dataTask中的JSON和字典进行Swift 3编译器错误 - Swift 3 Compiler Errors with JSON and Dictionaries within URLSession.shared.dataTask 使用 URLSession.shared.dataTask 发出 api 请求 - Making an api request using URLSession.shared.dataTask 如何获取请求中标头的值(URLSession.shared.dataTask(with:request){(数据,响应,错误) - How get value of headers in request (URLSession.shared.dataTask(with: request) { (data, response, error) 如果我在页面完成之前退出页面,如何取消 URLSession.shared.dataTask? - How can I cancel the URLSession.shared.dataTask if I exit the page before it completes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM