ALAMOFIRE发布请求图像并在集合视图中进行绑定

时间:2018-07-10 10:16:09

标签: ios swift alamofire

嗨,我是ios开发的新手,请引导我,我创建了一个带有参数的alamofire发布请求,我对此没有任何问题。之后,我需要从生成的Json响应中下载图像url,我不知道如何从json下载图像url并将其保存在数组中,之后必须从url下载图像并将其绑定到图像中集合视图。 我不知道如何从json响应中获取图像url,然后将其保存在数组中,然后必须下载图像将其绑定在集合视图中。 请帮助我

我已经更新了我在项目中编写的api类,它正在从url中正确获取数据,而且我不知道如何将其解析为集合视图单元格图像

 func apiclass(){

    if(globalConstants.prefs.value(forKey: "authToken") == nil){
        self.httpObj.getAuthToken()
    }
    else if(globalConstants.prefs.value(forKey: "authExpireDate") != nil && Date().compare((globalConstants.prefs.value(forKey: "authExpireDate") as? Date)!) == ComparisonResult.orderedDescending){
        globalConstants.prefs.setValue(nil, forKey: "authToken")
        self.httpObj.getAuthToken()
    }

    DispatchQueue.main.async(execute: {
        if(globalConstants.prefs.value(forKey: "authToken") != nil){
            var request:NSMutableURLRequest = NSMutableURLRequest(url: globalConstants.tokenUrl as URL)
            let authToken:String = (globalConstants.prefs.value(forKey: "authToken") as? String)!
            request = NSMutableURLRequest(url: globalConstants.tokenUrl as URL)
            request.addValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
            request.addValue(UIDevice.current.identifierForVendor!.uuidString, forHTTPHeaderField: "X-Device-ID")
            request.addValue((globalConstants.prefs.value(forKey: "UUID") as? String)!, forHTTPHeaderField: "X-Unique-ID")
            request.addValue((globalConstants.prefs.value(forKey: "countryCode") as? String)!, forHTTPHeaderField: "X-Country-Code")
            request.addValue((globalConstants.prefs.value(forKey: "currencyCode") as? String)!, forHTTPHeaderField: "X-Currency-Code")
            request.addValue((globalConstants.prefs.value(forKey: "currencySymbol") as? String)!, forHTTPHeaderField: "X-Currency-Symbol")
            request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "currencyFactor"))!), forHTTPHeaderField: "X-Currency-Factor")
            request.addValue((globalConstants.prefs.value(forKey: "appSource") as? String)!, forHTTPHeaderField: "X-App-Source")
            request.addValue(globalConstants.appVersion, forHTTPHeaderField: "X-App-Version")
            request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "estoreId") as? Int)!), forHTTPHeaderField: "X-EStore-ID")

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            if(globalConstants.prefs.value(forKey: "userEmail") != nil){
                request.addValue((globalConstants.prefs.value(forKey: "userEmail") as? String)!, forHTTPHeaderField: "X-Email")
            }
            if(globalConstants.prefs.value(forKey: "userId") != nil){
                request.addValue(String(stringInterpolationSegment: (globalConstants.prefs.value(forKey: "userId"))!), forHTTPHeaderField: "X-User-ID")
            }

            print(self.apiRequestParameters)

            var requestParameters:NSMutableDictionary = NSMutableDictionary()
            requestParameters = [

                "mode" : "design",
                "productGroup" : 0

            ]

            print(requestParameters)

            request.url = globalConstants.ESDCUrl as URL

            self.httpObj.sendRequest("POST", requestDict: requestParameters, request: request as URLRequest, completion: { (result, error) in
                print(result!)



                if(error == nil){

                    // move to shopping cart


                  //  dictResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary

                    self.dictResult = result as! NSArray

                    self.categorycollectionview.reloadData()




                    //self.collectionView.reloadData()

//让requestDataDict:NSDictionary = entryRequetArray [0]为! NSDictionary //让newDict:NSURL = requestDataDict.object(forKey:“ ImageUrl”)为? NSDictionary //

                }
                else{
                    let alert = UIAlertView()
                    alert.isHidden = true
                    alert.addButton(withTitle: "OK")
                    alert.message = globalConstants.apiErrorMessage
                    alert.show()
                }
            })
        }
    })

}

我已经为我的帖子请求更新了json响应。请给我一个解决方案。我可以在控制台中获得以下响应。

(   {
    ActualPrice = 0;
    AssuredTitle = "<null>";
    CashBackAmount = 0;
    CashBackDiscountPercentage = 0;
    Code = "";
    Cost = "<null>";
    CreateDate = "<null>";
    CustomSize = 0;
    Delivery = "<null>";
    DeliveryDate = "<null>";
    DeliveryDays = "<null>";
    Designer = "<null>";
    Discount = "<null>";
    DiscountCost = "<null>";
    DispatchDateDisplay = "<null>";
    Exclusive = "<null>";
    Gender = "<null>";
    HasReadyMadeColor = 0;
    HasReadyMadeSizes = 0;
    ID = 41;
    ImageUrl = "https://images.cbazaar.com/images/aqua-blue-georgette-abaya-isbs1805991-u.jpg";
    Is7DD = "<null>";
    IsCustomizable = 0;
    IsExclusive = 0;
    IsFree = "<null>";
    IsFreeShipping = 0;
    IsInWishlist = 0;
    IsLookUp = 0;
    IsNew = 0;
    IsProductAnimation = 0;
    IsReadyToShip = 0;
    LargeImageUrl = "<null>";
    ListingImage = "<null>";
    LowerLargeImage = "<null>";
    LowerThumbImage = "<null>";
    MoneyFactor = "<null>";
    MoneyOffFactor = "<null>";
    Name = "Islamic wear";
    OfferImageUrl = "<null>";
    OldPrice = 0;
    OutOfStock = 0;
    PDUrl = "<null>";
    ProductBigLink = "<null>";
    ProductCollectionReference = "<null>";
    ProductHisImage = "<null>";
    ProductSaleCycle = 0;
    ProductType = 168;
    ProductV2VRatio = 0;
    PromotionTypeID = "<null>";
    Promotions = "<null>";
    PromotionsIcon = "<null>";
    Rating = "<null>";
    SalePrice = "<null>";
    ShowOldPrice = 0;
    SizeChart = "<null>";
    SuperClassification = "<null>";
    TypeGroup = "<null>";
    TypeShortCode = "<null>";
    UpperLargeImage = "<null>";
    UpperThumbImage = "<null>";
    VendorType = "<null>";
    VisitCount = 0;
})

1 个答案:

答案 0 :(得分:0)

尝试

class dataModel{
let profImage: String?
let name: String?
init(profImg: String,name: String)
self.profImage = profImg
self.name = name
}

在CollectionViewController中

let arrayModel = [dataModel]()

After you got the image url add data to array

let dataAll = (dataModel[profImg: YourImageVariable, name: yourNameVariable])
arrayModel.append(dataAll)



    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellname", for: indexPath) as? yourCell {
   let dataIndex = dataModel[indexPath.row]
              cell.updateUI(setMdata: dataIndex)
            return cell


    }

    }

在单元格类中导入SDWebImage

class myCell: UICollectionViewCell {
     @IBOutlet weak var name: UILabel!
    @IBOutlet weak var profImage: UIImageView!
func updateUI(setMdata: dataModel) {
name.text = dataModel.name
profImagesd._setImage(with: URL(string:dataModel.profImg), placeholderImage: nill)

}
}