Tuesday, 13 January 2015

Post data to server in iOS [Image + data fields ]


// URL
NSString *strURL = [SiteAPIURL stringByAppendingFormat:@"AddChild.php"];


// field values to post [text]
NSDictionary *parameterToAdd = @{@"UserId":userID,
@"ChildFName":[txtViewFName.text trim],
@"ChildLName":[txtViewLName.text trim],
@"SafetyZone":isSafetyZone?@"YES":@"NO",
@"AlarmTone":lblAlarmToneName.text,
@"ChildId":@"0"};

// image to post [Data / image ] ==>>is used to send image;
UIImage *imgToSend = imgViewPickerPhoto.image;
[postBody appendData:[@"Content-Disposition: form-data; name=\"Image\"; filename=\"image.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


whole code



- (void)btnSavePressed {
    pro(@"save pressed");
    if ([self validateForm]) {
        [mainWindow addSubview:HUD];
        [HUD showWhileExecuting:@selector(sendAddChildInfoToServer)
                       onTarget:self
                     withObject:nil
                       animated:YES];
    }
}
- (BOOL)validateForm {
    if ([Validate isNull:txtViewFName.text]) {
        [CommonFunctions AlertWithMsg:@"Please enter a first name."];
    } else if ([Validate isNull:txtViewLName.text]) {
        [CommonFunctions AlertWithMsg:@"Please enter a last name."];
    } else {
        return YES;
    }
    return NO;
}

- (void)sendAddChildInfoToServer {

    NSString *strURL = [SiteAPIURL stringByAppendingFormat:@"AddChild.php"];
    pro(strURL);
    

    NSDictionary *parameterToAdd = @{@"UserId":userID,
                                     @"ChildFName":[txtViewFName.text trim],
                                     @"ChildLName":[txtViewLName.text trim],
                                     @"SafetyZone":isSafetyZone?@"YES":@"NO",
                                     @"AlarmTone":lblAlarmToneName.text,
                                     @"ChildId":@"0"};
 

    UIImage *imgToSend = imgViewPickerPhoto.image;
      

    //setup url
    NSURL *siteURL = [[NSURL alloc] initWithString:[strURL stringByURLEncode]];
    
    // create the connection
    NSMutableURLRequest *siteRequest = [NSMutableURLRequest requestWithURL:siteURL
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:30.0];
    
    [siteRequest setHTTPMethod:@"POST"];
    
    
    NSMutableData *postBody = [NSMutableData data];
    
    
    // set Content-Type in HTTP header
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [siteRequest setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    
    // add params (all params are strings)
    for (NSString *param in parameterToAdd) {
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterToAdd[param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    ////---- add image
    if (isHasImage && imgToSend) {
        // add image data
        NSData *imageData =UIImageJPEGRepresentation(imgToSend, 0);
        if (imageData) {
            [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Disposition: form-data; name=\"Image\"; filename=\"image.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [postBody appendData:imageData];
            [postBody appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // add body to post
    [siteRequest setHTTPBody:postBody];
    
    [siteRequest setValue:[NSString stringWithFormat:@"%u", [postBody length]] forHTTPHeaderField:@"Content-Length"];
    
    
    NSURLResponse *response;
    NSError *error;
    if ([CommonFunctions isNetworkConnect]) {
        NSData *returnData = [NSURLConnection sendSynchronousRequest:siteRequest
                                                   returningResponse:&response
                                                               error:&error];
        
        NSString *returnString = [[NSString alloc] initWithData:returnData
                                                       encoding:NSUTF8StringEncoding];
        
        returnString = [returnString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        
        if (![NSThread isMainThread]) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                if (!error && returnString) {
                    NSError *error;
                    NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding]
                                                                       options:NSJSONReadingMutableContainers
                                                                         error:&error];
                    NSLog(@"%@, error %@",dic,error);
                    if (dic && !error)
                    {
                        // play with dic : server response
                        if ([dic[@"Response"] isEqualToString:@"success"]) {
                            // do something
                            [CommonFunctions AlertWithMsg:dic[@"Message"]];
                        } else if ([dic[@"Response"] isEqualToString:@"failure"]) {
                            [CommonFunctions AlertWithMsg:dic[@"Message"]];
                        } else {
                            [CommonFunctions serverInternalError];
                        }
                    } else {
                        [CommonFunctions showServerNotFoundError];
                    }
                }
                else{
                    [CommonFunctions showServerNotFoundError];
                }
            });
        }
    }
}

No comments:

Post a Comment