отправить массив в API в Swift 4 - PullRequest
0 голосов
/ 11 июля 2019

Я хочу отправить параметр в свой собственный API. у моего параметра есть массив. моя проблема в том, что все в моем параметре сохраняется, кроме моего массива. вот мой параметр:

                parameters = ["id" : accommodation.id , "title" : accommodation.title , "address_comment": accommodation.address_comment , "about": accommodation.about , "accommodation_amenities" : accomodationAmenty , "accommodation_important_places" : importantPlace  ] as [String : Any]

«Проживание_удобства» и «Проживание_импорта_пласы» - это мои Арричи.

Я заполняю свои массивы этим методом:

        var accomodationAmenty:NSMutableArray = NSMutableArray()
    var prod: NSMutableDictionary = NSMutableDictionary()
    for item in accommodation.AccommodationAmenitiesList{

        prod = NSMutableDictionary()
        prod.setValue(String(item.amenity_id), forKey: "amenities_id ")
        prod.setValue(String(item.accommodation_id), forKey: "accommodation_id")
        prod.setValue(" ", forKey: "comment")
        accomodationAmenty.add(prod)
    }

    var importantPlace:NSMutableArray = NSMutableArray()
    var prod1: NSMutableDictionary = NSMutableDictionary()
    for item in accommodation.ImportantPlace{

        prod1 = NSMutableDictionary()
        prod1.setValue(String(item.accommodation_id), forKey: "accommodation_id")
        prod1.setValue(String(item.id), forKey: "important_place_id ")
        prod1.setValue(String(item.distance), forKey: "distance")
        importantPlace.add(prod1)
    }

вот как я подключаюсь к своему API:

       let request = NSMutableURLRequest(url: NSURL(string: FixedVariable.serverUrlAddress + "my api")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpBody = postData as Data
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers




    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        guard let httpResponse = response as? HTTPURLResponse,
            httpResponse.statusCode == 200 else {

                var httpResponse = response as? HTTPURLResponse
                if(httpResponse?.statusCode == 401){

                    DispatchQueue.main.async {

                        return
                    }
                }

                print(error)
                self.hideLoading()
                DispatchQueue.main.async {
                    self.showMassageBox(messageString: "can't connect to Server")
                }
                return
        }
        do {

            print(httpResponse)
            var jsonString = String()
            if(data != nil){

                jsonString = String(data:data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
                self.jsonSerialize(jsonString: jsonString)

            }



        } catch {
            print("bad things happened")
        }
    })

    dataTask.resume()

и это мой код:

    func connectToServer()
{
    showLoading()
    var token = "..."
    let headers = [
        "content-type": "application/x-www-form-urlencoded",
        "api-secret-key": "...",
        "Authorization": "...",
        "cache-control": "no-cache",
        "postman-token": "..."]

    var postData = Data()
    var accomodationAmenty:NSMutableArray = NSMutableArray()
    var prod: NSMutableDictionary = NSMutableDictionary()
    for item in accommodation.AccommodationAmenitiesList{

        prod = NSMutableDictionary()
        prod.setValue(String(item.amenity_id), forKey: "amenities_id ")
        prod.setValue(String(item.accommodation_id), forKey: "accommodation_id")
        prod.setValue(" ", forKey: "comment")
        accomodationAmenty.add(prod)
    }

    var importantPlace:NSMutableArray = NSMutableArray()
    var prod1: NSMutableDictionary = NSMutableDictionary()
    for item in accommodation.ImportantPlace{

        prod1 = NSMutableDictionary()
        prod1.setValue(String(item.accommodation_id), forKey: "accommodation_id")
        prod1.setValue(String(item.id), forKey: "important_place_id ")
        prod1.setValue(String(item.distance), forKey: "distance")
        importantPlace.add(prod1)
    }

    do{

        var parameters : [String : Any]? = nil
        if(isEdite == true){

            parameters = ["id" : accommodation.id , "title" : accommodation.title , "address_comment": accommodation.address_comment , "about": accommodation.about , "accommodation_amenities" : accomodationAmenty , "accommodation_important_places" : importantPlace  ] as [String : Any]
        }
        else{


            parameters = [ "title" : accommodation.title , "address_comment": accommodation.address_comment , "about": accommodation.about , "accommodation_amenities" : accomodationAmenty , "accommodation_important_places" : importantPlace  ] as [String : Any]
        }
        postData = try JSONSerialization.data(withJSONObject: parameters, options: [])
    }
    catch{

    }

    let request = NSMutableURLRequest(url: NSURL(string: FixedVariable.serverUrlAddress + "my api")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpBody = postData as Data
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers


    //self.timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(showView), userInfo: nil, repeats: true);

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        guard let httpResponse = response as? HTTPURLResponse,
            httpResponse.statusCode == 200 else {

                var httpResponse = response as? HTTPURLResponse
                if(httpResponse?.statusCode == 401){

                    DispatchQueue.main.async {

                        return
                    }
                }

                print(error)
                self.hideLoading()
                DispatchQueue.main.async {
                    self.showMassageBox(messageString: "can't connect to Server")
                }
                return
        }
        do {

            print(httpResponse)
            var jsonString = String()
            if(data != nil){

                jsonString = String(data:data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
                self.jsonSerialize(jsonString: jsonString)

            }



        } catch {
            print("bad things happened")
        }
    })

    dataTask.resume()

}
...