Alamofire上传返回JSON

时间:2017-05-14 20:27:55

标签: swift reflection alamofire

在Alamofire.upload调用中获取结果数据的问题。

我使用以下代码将多部分表单数据发送到服务器:

   sessionManager.upload(
            multipartFormData: { multipartFormData in
                if let name = currentPlace.name,
                    let data = name.data(using:String.Encoding.utf8) {
                    multipartFormData.append(data, withName: "placename", mimeType: "text/plain")
                }
                if let lat = currentPlace.location?.coordinate.latitude {
                    multipartFormData.append(String(describing: lat).data(using:String.Encoding.utf8)!, withName: "latitude", mimeType: "text/plain")
                }
                if let lon = currentPlace.location?.coordinate.longitude {
                    multipartFormData.append(String(describing: lon).data(using:String.Encoding.utf8)!, withName: "longitude", mimeType: "text/plain")
                }

                multipartFormData.append((User.current.scanMode.rawValue).data(using:String.Encoding.utf8)!, withName: "state", mimeType: "text/plain")
        },
            to: (url?.absoluteString)!,  headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):


                    upload.responseJSON { response in

                        print(response.request)  // original URL request
                        print(response.response) // URL response
                        print(response.data)     // server data
                        print(response.result)   // result of response serialization

                        if let JSON = response.result.value as? NSArray {
                            for element in JSON {
                                print(element)
                            }
                        }

                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
        })

我的挑战是以我可以验证的形式获取response.result.value的值。当前的调试输出是:

(lldb) po response.result.value
▿ Optional<Any>
  ▿ some : 4 elements
    ▿ 0 : 2 elements
      - key : code
      - value : 200
    ▿ 1 : 2 elements
      - key : id
      - value : 78230c53954a3adbf14b49cda127bf55
    ▿ 2 : 2 elements
      - key : message
      - value : Successfully updated OID to DISTRIBUTED.
    ▿ 3 : 2 elements
      - key : state
      - value : DISTRIBUTED

看起来像一个数组,但似乎无法将其投射或反映到我可以使用的东西中。通常我会使用EVOReflection获取此数据,如下所示:

 sessionManager.request((url?.absoluteString)!, method: .get, parameters: postParameters, encoding: URLEncoding.httpBody, headers: headers)
            .responseObject { (response: DataResponse<AssetStateResponse>) in
                if let response = response.result.value {
                    completionHandler(response)
                } else {
                    // LATER: Better error handling
                }
        }

任何帮助表示赞赏,现在已经看了好几天,遗漏了一些我怀疑的简单。

3 个答案:

答案 0 :(得分:1)

respose.result.value看起来像个字典,而不是数组。

你尝试过那种方式吗?

if let jsonDict = response.result.value as? NSDictionary {
   print(jsonDict)
}

答案 1 :(得分:0)

Alamofire回复将导致字典。

所以你的response.result.value是一本字典

print(response.result)此行之后调用函数funcJSONParsing

self.funcJSONParsing(response.result.value!)

将解析写在一个单独的函数中,如下所示。

func funcJSONParsing(let json:AnyObject)
    {
        if json is NSDictionary{

            let jsonResponse = json as! NSDictionary
            //Parse the below jsonResponse according to your needs
            }
     }

答案 2 :(得分:0)

from django.shortcuts import render
from django.views.generic.edit import FormView
from .forms import HomeForm

class FormView1(FormView):
    template_name = 'index.html'
    # form_class = RequiredInputsForm
    # success_url = '/index/success/'

    def get(self, request):
        form = HomeForm()
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = HomeForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()

            phone = form.cleaned_data['post']
            form = HomeForm()
            return redirect('index:index')

            args = {'form': form, 'text': text}
            return render(request, self.template_name, args)