如何使用ios中的NSURLConnection将文本和图像发送到服务器

时间:2015-12-01 09:52:52

标签: ios objective-c nsurlconnection

您好我是Ios的初学者,在我的项目中,我需要使用NSURLConnection向服务器发送“用户名”,“密码”和“用户图像”,为此我已经插入了这三个字段(用户名,密码,用户图片)一个字典,我将这个字典发布到服务器,但使用我的下面的代码详细信息不发送到服务器,请帮助我,我做错了什么

我的代码: -

@interface SendingImagesToServer ()
{
    NSMutableData *body;
}
@end

@implementation SendingImagesToServer

- (void)viewDidLoad {
    [super viewDidLoad];

    NSData *imageData;
    UIImage * image;
    NSError *error = nil;
    image = [UIImage imageNamed:@"friendship.jpg"];
    imageData = UIImageJPEGRepresentation(image, 0.1f);

    NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"James"  ,@"username",
                              @"1234",@"Password",
                              imageData,@"image",
                              nil];

    NSString *jsonString = [mainDict JSONRepresentation];

    NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    body = [webbody mutableCopy];

    NSString *urlstr = [NSString stringWithFormat:@"My url here"];

    NSURL *url = [NSURL URLWithString:urlstr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];

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

    body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    if(imageData == nil && error!=nil) {
        NSLog(@"nil");
    }
    else
    {
        NSLog(@"not nill");
    }

    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Successfully sending to server");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"error is %@",[error localizedDescription]);
}

@end

1 个答案:

答案 0 :(得分:-1)

您创建了请求,但不要在代码中的任何位置启动它。您也不能在任何地方创建NSURLConnection(至少不在发布的部分中)。

实现此目标的最简单方法是在viewDidLoad方法的末尾添加此行:

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

您可以阅读更多here