簡體   English   中英

如何在 Swift 中使用 Alamofire 上傳帶有 JSON 參數的圖像?

[英]How can I upload image with JSON parameters with Alamofire in Swift?

我需要將圖像上傳到結構必須如下的服務器端點:

    {
        "name": "",
        "description": "",
        "photo": imageFile
    }

如何使用 Alamofire 發送此類請求?

我試過了,但結果是錯誤消息Invalid type in JSON write (NSConcreteData)這是我的代碼:

    let imageData = UIImagePNGRepresentation(image)
    let base64String = imageData!.base64EncodedDataWithOptions([])
    
    let parameters = [
        "name": "name",
        "description": "desc",
        "photo": base64String
    ]
    
    let credentialData = "\(id):\(secret)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (response) -> Void in
        print(response)
    }

我跟着這個代碼

如果有其他方法請指教,謝謝。

我正在使用的這個方法你可能會發現它很有用

let image : UIImage = image.image!
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM