将HTTP Body设置为AFNetworking而不是使用本机请求

时间:2016-01-21 07:29:17

标签: ios swift http afnetworking

我最近一直试图让AFNetworking像我对本机请求一样工作,我一直使用AFNetworking上传POST或GET。但它从来没有正确上传我的图像。它总是上传到损坏的服务器,我已在此参考中解释了该问题:Uploading image to server reached damaged using AFNetworking

我已尝试将本机NSURLConnection.sendSynchronousRequest与HTTP正文一起使用,并且已上传且未损坏。并且这段代码完全有效但我在AFNetworking中需要它,因为它只支持IOS 8 +并且有更多原因。

        let baseURL = ""
        let selectedImage = self.userImage.image
        let imageData = NSData(data: UIImageJPEGRepresentation(selectedImage!, 0.5)!)

        let request = NSMutableURLRequest()
        request.URL = NSURL(string: baseURL)
        request.HTTPMethod = "POST"
        request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
        let body = NSMutableData(data: imageData)
        request.HTTPBody = body

 do {
            let responseData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:nil)
            let responseString = String(data: responseData, encoding: NSUTF8StringEncoding)

            print("User image successfully uploaded navigating to home services")


        } catch (let error as NSError) {
}

2 个答案:

答案 0 :(得分:0)

以下是Objective-c中的解决方案,也为swift复制相同的过程。 为select day(Ser_CallDate) as OrderDate, count(*) TotalCall from ServiceCalls where month(Ser_CallDate) = MONTH(getdate()) and year(Ser_CallDate) = YEAR(getdate()) group by day(Ser_CallDate) 创建一个对象,如下所示。

AFHTTPRequestOperationManager

现在使用键值对定义 [[AFHTTPRequestOperationManager alloc] initWithBaseURL:@"www.google.com"]; ,键值对将是您的请求正文的参数。

NSDictionary

现在,在致电NSDictionary *parameters = @{ @"paramaname": value, @"paramaname":value }; 请求时

POST

这是使用 [self.manager POST:@"someMethodName" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary * responseDict = (NSDictionary *)responseObject; NSLog(@"responseDict : %@",responseDict); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error : %@ code %d",error.localizedDescription,error.code); } }]; 发送带有参数的POST请求的方法。

答案 1 :(得分:0)

     NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
    [contentDictionary setValue:@"name" forKey:@"email"];
    [contentDictionary setValue:@"name" forKey:@"username"];
    [contentDictionary setValue:@"name" forKey:@"password"];
   [contentDictionary setValue:@"name" forKey:@"firstName"];
    [contentDictionary setValue:@"name" forKey:@"lastName"];

    NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager    HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

尝试这个