2016-05-23 51 views
5

我想Int值添加到multipartFormData如何int值添加到Alamofire參數上傳

Alamofire.upload(.POST, 
       url, 
       headers: headers, 
       multipartFormData: { multipartFormData in 
        //add some jpg image 
        //add other vaues: 
        for (key, value) in parameters { 
         if value is String { 
          multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) 
         } else if value is Int { 
          let convertedValueNumber: NSNumber = NSNumber(int: value.intValue) 
          let data = NSKeyedArchiver.archivedDataWithRootObject(convertedValueNumber) 
          multipartFormData.appendBodyPart(data: data, name: key) 
         } 
        } 

    }, encodingCompletion: { encodingResult in 
     //some processing 
}) 

但是,我不送Int值服務器返回錯誤。如何將Int值添加到參數中?

+0

您可以選擇將類型轉換爲字符串。 –

+0

你的服務器真的在期待'NSKeyedArchiver'二進制plist?!?大多數時候,服務器只會期望數字值的字符串表示。 – Rob

+0

@Rob我試圖轉換沒有NSKeyedArchiver我用數據= NSData(字節:&vInt,長度:sizeof(Int))multipartFormData.appendBodyPart(數據:數據,名稱:鍵)這並沒有幫助 –

回答

12

NSKeyedArchiver非常好奇。通常你只要發送字符串表示,例如:

Alamofire.upload(.POST, URL, headers: headers, multipartFormData: { multipartFormData in 
    //add some jpg image 
    //add other values: 
    for (key, value) in parameters { 
     if value is String { 
      multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key) 
     } else if value is Int { 
      multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key) 
     } 
    } 
}, encodingCompletion: { encodingResult in 
    //some processing 
}) 

甚至更​​簡單,因爲串插既StringInt工作:

Alamofire.upload(.POST, URL, headers: headers, multipartFormData: { multipartFormData in 
    //add some jpg image 
    //add other values: 
    for (key, value) in parameters { 
     if value is String || value is Int { 
      multipartFormData.appendBodyPart(data: "\(value)".dataUsingEncoding(NSUTF8StringEncoding)!, name: key) 
     } 
    } 
}, encodingCompletion: { encodingResult in 
    //some processing 
}) 

或者,在Alamofire 4斯威夫特3:

Alamofire.upload(multipartFormData: { multipartFormData in 
    //add some jpg image 
    //add other values: 
    for (key, value) in parameters { 
     if value is String || value is Int { 
      multipartFormData.append("\(value)".data(using: .utf8)!, withName: key) 
     } 
    } 
}, to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in 
    //some processing 
}) 
+0

謝謝,但我有一個問題,如果值可能是'[String]','[String:Any]'...如果可能有多種類型,我應該爲每種類型創建is塊嗎? – Chlebta

+1

或者你可以讓這個方法接受兩個排列,例如'Any?'參數,然後做'如果讓參數=參數爲? [String] {...}否則,如果讓參數=參數爲? [String:String] {...}',或其他。 – Rob