简体   繁体   English

如何使用Swift 3和Alamofire从JSON下载图像?

[英]How to download image from JSON using the Swift 3 and Alamofire?

How to download image from JSON using Alamofire and Swift 3? 如何使用Alamofire和Swift 3从JSON下载图像? I am getting dictionary of data. 我正在获取数据字典。 See the following JSON response. 请参阅以下JSON响应。 I am able to print data in labels but I can't download the image. 我可以在标签中打印数据,但无法下载图像。 This is the response I am getting from the API. 这是我从API得到的响应。

userJson userJson userJson userJson ["status": 1, "student": { "admission_date" = "14/06/2017"; userJson userJson userJson userJson [“状态”:1,“学生”:{“ admission_date” =“ 14/06/2017”; "admission_no" = 13538; “ admission_no” = 13538; "class_teacher" = "Caroline Forbes"; “ class_teacher” =“卡罗琳·福布斯”; dob = dob =
"04/05/2001"; “ 04/05/2001”; email = "ranisagar.sivadas@gmail.com"; 电子邮件=“ ranisagar.sivadas@gmail.com”; "father_name" = "SAGAR SIVADAS"; “ father_name” =“ SAGAR SIVADAS”; gender = Male; 性别=男性; image = 图片=
"/system/images/86/j1f9DiJi_medium.jpg?1504593436"; “ /system/images/86/j1f9DiJi_medium.jpg?1504593436”; "mother_name" = "RANI RS"; “ mother_name” =“ RANI RS”; name = "Abhijith Sagar"; 名称=“阿比吉斯·萨加尔”; phone = 9066260799; 电话= 9066260799; religion = Hindu; 宗教=印度教; "school_email" = "13538.861@demo.in"; “ school_email” =“ 13538.861@demo.in”; "student_id" = 86; “ student_id” = 86; }, },
"message": Details fetched successfully.] “消息”:详细信息已成功获取。]

This is my code. 这是我的代码。

func SetUpUIProfiledata() {
    APIManager.sharedInstance.getParentDataFromURL(){(userJson)-> Void in
        let swiftyJsonVar = JSON(userJson)
        print("userJson userJson userJson userJson",userJson)
        print("swiftyJsonVar",swiftyJsonVar)
        let message = swiftyJsonVar["message"].rawString()
        let sudent = swiftyJsonVar["student"].rawString()!
        let jsonData = sudent.data(using: .utf8)!
        let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>
        self.name_lbl.text = dictionary?["name"] as? String
        self.fatherName_lbl.text = dictionary?["father_name"] as? String
        self.motherName_lbl.text = dictionary?["mother_name"] as? String
        self.phone_lbl.text = dictionary?["phone"] as? String
        self.email_lbl.text = dictionary?["email"] as? String
        self.dob_lbl.text=dictionary?["dob"] as? String
        self.gender_lbl.text=dictionary?["gender"] as? String
        self.religion_lbl.text=dictionary?["religion"] as? String
        self.admissionDate_lbl.text=dictionary?["admission_date"] as? String
        self.admissionNum_lbl.text=dictionary?["admission_no"] as? String
        self.schoolMail_lbl.text=dictionary?["school_email"] as? String
        self.teacher_lbl.text=dictionary?["class_teacher"] as? String
    }
}

Have a look at below code you just need to pass a link url to alamofire and you can download a image . 看下面的代码,您只需要将链接URL传递给alamofire,就可以下载图像。 if its not the expected answer please Re edit your question . 如果不是预期的答案,请重新编辑您的问题。

       let strURL1:String = "https://www.planwallpaper.com/static/images/9-credit-1.jpg"
Alamofire.request(strURL1).responseData(completionHandler: { response in
    debugPrint(response)

    debugPrint(response.result)

    if let image1 = response.result.value {
        let image = UIImage(data: image1)
         self.imageView.image = image

    }
})

I looked at output you had provided you are getting 我查看了您提供的输出

 image =
"/system/images/86/j1f9DiJi_medium.jpg?1504593436";

is this a valid url or path if its a url you need to add your base url + your " /system/images/86/j1f9DiJi_medium.jpg?1504593436" and pass it to alamofire block to download image as in my above example 这是一个有效的网址或路径吗(如果它是一个网址),您需要添加base url + your " /system/images/86/j1f9DiJi_medium.jpg?1504593436"并将其传递给alamofire块以下载图片,如上面的示例所示

"https://www.planwallpaper.com" - baseURl
"static/images/9-credit-1.jpg" - image Path as in your case

Hope it helps. 希望能帮助到你。

First get the image key corresponding value & marge it with your base URL. 首先获取图像键对应的值,并将其与您的基本URL匹配。 Like 喜欢

let url = "www.yourbaseurlhere.com" + "/system/images/86/j1f9DiJi_medium.jpg?1504593436"

Now create a destination path for it like 现在为它创建一个目标路径

let destination = DownloadRequest.suggestedDownloadDestination(
     for: .documentDirectory,
     in: .userDomainMask
 )

Now use Alamofire download method like 现在使用Alamofire下载方法,例如

Alamofire.download(url, to: destination)
     .downloadProgress { progress in
            print("Download Progress: \(progress.fractionCompleted)")
         }
         .responseData { response in
             if response.result.value != nil {
                   if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as? URL {

                        let fileName = response.response?.suggestedFilename // get your file name here.
                        let finalPath = directoryURL.appendingPathComponent(fileName!) //get your file path here
                    }
              }
         }

Hope it helps. 希望能帮助到你。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM