Upload image to web service in ios

Viewed 3205

I tried AFNetworking's "Create an upload task" and this to upload image in .net server, but couldn't. This is what I tried.

- (void)uploadJPEGImage:(NSString*)requestURL image:(UIImage*)image
{
    NSURL *url = [[NSURL alloc] initWithString:requestURL];
    NSMutableURLRequest *urequest = [NSMutableURLRequest requestWithURL:url];

    [urequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [urequest setHTTPShouldHandleCookies:NO];
    [urequest setTimeoutInterval:60];
    [urequest setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [urequest setValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    // add image data
    NSData *imageData = UIImageJPEGRepresentation(qrCodeImage.image, 1.0);
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        //[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", pictureName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [urequest setHTTPBody:body];
    NSLog(@"Check response if image was uploaded after this log");
    //return and test
    NSData *returnData = [NSURLConnection sendSynchronousRequest:urequest returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", returnString);

}

Since AFNetworking code gives, me this run time error despite adding

self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", @"text/html", nil];

Thanks.

2 Answers
Related