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

时间:2017-09-12 04:36:24

标签: ios json swift image alamofire

如何使用Alamofire和Swift 3从JSON下载图像?我正在获取数据字典。请参阅以下JSON响应。我能够在标签中打印数据,但我无法下载图像。这是我从API获得的响应。

  

userJson userJson userJson userJson [“status”:1,“student”:{“admission_date”=“14/06/2017”;       “admission_no”= 13538; “class_teacher”=“卡罗琳福布斯”; dob =
      “2001年4月5日”; email =“ranisagar.sivadas@gmail.com”; “father_name”=       “SAGAR SIVADAS”;性别=男性; image =
      “/system/images/86/j1f9DiJi_medium.jpg?1504593436”; “mother_name”=       “RANI R S”; name =“Abhijith Sagar”;电话= 9066260799;宗教=       印度; “school_email”=“13538.861@demo.in”; “student_id”= 86; },
      “message”:已成功获取详细信息。]

这是我的代码。

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

2 个答案:

答案 0 :(得分:1)

查看以下代码,您只需将链接网址传递给alamofire即可下载图片。如果不是预期的答案,请重新编辑您的问题。

       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

    }
})

我查看了你提供的输出

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

这是一个有效的网址或路径,如果它是一个网址,您需要添加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

希望它有所帮助。

答案 1 :(得分:1)

首先获取图像键对应的值&amp;用你的基本URL来表达它。像

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

现在为它创建一个目标路径,如

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

现在使用像

这样的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
                    }
              }
         }

希望它有所帮助。