UIPregressView Upload Image with AFNetWorking - ios

I'm new in iOS Development. I create Upload Image Method with "AFNetworking". And I want to Add UIProgressView when Processing.
Now I use "DejalBezelActivityView" in my Upload Method
"DejalBezelActivityView" is worked but i want to use UIProgressView.
How to do it?
This is Example of my code:
-(void) uploadImage
{
// Set Data to Web API
// NSMutableArray *newPictureData = ...
// WEB API
[PictureClient uploadPictures:newPictureData whenCompleted:^(BOOL success, NSString *data, NSError *error)
{
if (success)
{
[DejalBezelActivityView removeViewAnimated:YES];
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#“Complete"
message:#“Upload Cpmplete"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[myAlertView show];
// Do somethings
// ...
}
else
{
[DejalBezelActivityView removeViewAnimated:YES];
// Error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“Error"
message:errorCode
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}];
[DejalBezelActivityView activityViewForView:self.view withLabel:#“During Picture"];
}

like #StatusReport answered with MBHudProgress
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:#"http://www.myurl.com"
parameters:dataToPost
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"attachment"
fileName:#"myimage.jpg"
mimeType:#"image/jpeg"];
}];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Failure %#", error.description);
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(#"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
}];
// 5. Begin!
[operation start];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];

Related

Unknown receiver 'AFHTTPRequestOperation' ; did you mean 'AFHTTPRequestSerializer'

I am learning AFNetworking kit. I followed this tutorial. Now I stuck at comment 2 see code below AFHTTPRequestOperation.
I imported AFNetworking using cocoapods.
Here is my code:
- (IBAction)jsonTapped:(id)sender{
// comment 1
NSString *string = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// comment 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// comment 3
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// comment 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// comment 5
[operation start];
}
Now getting error at compile time see screen shot:
Please make sure that you included AFNetworking properly inside your project before you import any of the AFNetworking class. Probably you have not imported the kit properly.
Dont use UIAlertView which is deprecated iOS 9 use UIAlertController see code below.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"text mssg" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
// Ok action code here
}];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:#"Other" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
// Other action code here
}];
[alert addAction:okAction];
[alert addAction:otherAction];
[self presentViewController:alert animated:YES completion:nil];
You can use AFHTTPRequestOperationManager
- (void)apiRequestForPOSTWithServiceName:(NSString *)serviceName andParameters:(NSDictionary *)parameter withCompletion:(void(^)(id response, BOOL isSuccess))completion
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *url = [NSString stringWithFormat:#"%#%#", BASE_URL, serviceName];
[manager POST:url parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
completion(responseObject,YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
completion(error,NO);
}];
}
Happy coding...!!

Google AutoComplete API getting "INVALID REQUEST"

I've to add google autocomplete api in my app but I don't know. I also getting "INVALID REQUEST". I also check developer.google.com but I can't find any solution. I am using AFNetwrok.
Here is my code
NSString *strURL = [NSString stringWithFormat:#"%#key=%#",AutoComplete_URL,GOOGLE_KEY];
NSDictionary *params = #{#"input" : [#"Paris" stringByReplacingOccurrencesOfString:#" " withString:#"+"],#"sensor":#"true"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:strURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
[APPDELEGATE hideLoadingView];
if ([[responseObject valueForKey:#"status"] isEqualToString:#"OK"]) {
arrAutocomplete = [[responseObject valueForKey:#"predictions"] valueForKey:#"description"];
NSLog(#"AUTO: %#", arrAutocomplete);
}
else{
// [APPDELEGATE showpToastWithTitle:[response valueForKey:#"msg"]];
//[self.tableView setHidden:YES];
}
}
else{
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Please check your internet connection"];
}
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Something going wrong"];
}];
OUTPUT :-
JSON:
{
predictions = (
);
status = "INVALID_REQUEST";
}
i got it.
NSString *string = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=%#&types=geocode&input=%#",GOOGLE_KEY,address];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"%#",responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];

operation failed in error: <AFHTTPRequestOperationManager: 0x80010ce0, baseURL: (null), operationQueue:

I am using AFNetworking Framework for calling API and sometimes I am not getting any response from server while API call:
Here is my code snippet:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager.requestSerializer setTimeoutInterval:timeOutInterval];
[manager POST:[NSString stringWithFormat:#"%#%#",MainUrl,apiName] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *arrData = responseObject;
NSLog(#"%#",arrData);
NSString *strCode = [NSString stringWithFormat:#"%#",[arrData valueForKey:#"success"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
NSLog(#"Error: %#", manager);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Message" message:#"Please check your internet connection" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}];
I get below error :
Error: <AFHTTPRequestOperationManager: 0x80010ce0, baseURL: (null), operationQueue: <NSOperationQueue: 0x80010ca0>{name = 'NSOperationQueue 0x80010ca0'}>
Any help will be appreciated.
In ios 9.1
AFNetworking 2.5

ASIFormDataRequest post method is not working in ios

Hi i am beginner in Ios and in my project there is facility for users "ForGotPassword" request
For this i have written some code but that is not working
i.e is objectFromJSONString response shows like -->Message: "No HTTP resource was found that matches the request URI "my url."
what did i do here wrong ,is it my problem or server side problem? please help me
my code:-
- (IBAction)submitBtnClicked:(id)sender {
NSLog(#"password ---->>> %#",self.MedicalIdTxt.text);
NSString *urlStr = [NSString stringWithFormat:#"my url"];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
[request setPostValue:self.MedicalIdTxt.text forKey:#"MedicaidId"];
[request setDelegate:self];
[request startAsynchronous];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"requestFinished");
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"%#",request);
NSString *receivedString = [request responseString];
NSLog(#"receivedString %#",receivedString);
NSDictionary * jsonObj=[[NSDictionary alloc]init];
jsonObj = [receivedString objectFromJSONString];
NSLog(#"jsonObj result is%#",jsonObj);
NSString *messageStr = [jsonObj objectForKey:#"message"];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"" message:messageStr delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSString *receivedString = [request responseString];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:receivedString message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
here "jsonObj" not showing response which is coming from services what did i do here wrong?
ASIHTTPRequest is not under maintenance since so long, so use AFNetworking instead:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"your url"
parameters:#{#"color": #"green"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

connection is nil file upload using afnetworking in iphone5s

I uploading a file using afnetworkin in app. It working on iphon4 but failed in iphon5s.
I'm getting connection == nil in while uploading.
Code :
-(void) uploadFile:(NSURL *)url withFileName:(NSString *)filename mimeType:(NSString *)mimeType {
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[self.navigationController.view addSubview:HUD];
// Set determinate mode
HUD.mode = MBProgressHUDModeAnnularDeterminate;
HUD.delegate = self;
HUD.labelText = #"Uploading";
progress = 0.0f;
[HUD showAnimated:YES whileExecutingBlock:^{
while (progress < 100) {
//progress += 0.01f;
HUD.progress = (float)progress/100.0;
usleep(50000);
}
}];
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSError *__autoreleasing *error = NULL;
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:kUploadAPI
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:url
name:#"uploadedfile"
fileName:filename
mimeType:mimeType error:nil];
} error:error];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
operation = [manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[HUD hide:YES];
// handle response
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[HUD hide:YES];
NSLog(#"Failure %#", error.description);
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
//NSLog(#"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
progress = (int)(((float)totalBytesWritten / totalBytesExpectedToWrite) * 100.0);
NSLog(#"Uploading...%d",(int)progress);
}];
// 5. Begin!
[operation start];
}
Getting error in delegate method using AFnetworking
- (void)connection:(NSURLConnection __unused *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.uploadProgress) {
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
});
}
Getting error in delegate method using NSUrlConnection
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
///here I'm getting connection == nil
}

Resources