I have a Mysevers Class for network written by Objective-c, and now I use mixed Objective-c and Swift project.
In my Mysevers, I have a method to network:
+(void)AFPOSTWithHud:(BOOL)hud andAddressname:(NSString*)addressName parmas:(NSDictionary*)parmas RequestSuccess:(void(^)(id result))success failBlcok:(void(^)(void))failBlcok
{
if (hud) {
[HUD addHUD];
}
AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];
NSString *urlStr = [NSString stringWithFormat:#"%#%#",BASE_URL,addressName];
NSLog(#"%#",urlStr);
[requestManager POST:urlStr parameters:parmas progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (hud) {
[HUD removeHUD];
}
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (error != nil) {
NSLog(#"error==%#",[error localizedDescription]);
if (hud) {
[HUD removeHUD];
}
}
failBlcok();
}];
}
In the Swift controller, invoke the method, pass a swift Bool value false.
Mysevers.afpost(withHud: false, andAddressname: Global.url_fillMoreInfo, parmas: uploadDict, requestSuccess:{ (result) in
But, in the Mysevers class, I give a breakpoint to check the passed value, it turn out to be YES:
(lldb) po hud
YES
Related
I,m trying to upload video using afnetworking and my code is below in response it return nil url please let me know if you want any other detail . i don,t know where is my mistake.
{
// add hud to show sending image
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSString *format;
format=#"video/mp4";
myDict1 = #{#"user_id”:””,
#"timezone”:””,
#"friend_id”:””,
#"message_type”:””,
#"message":"",
#"language_id”:””
};
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
NSString* webService=[NSString stringWithFormat:#"%#/send_messages",WEB_SERVICE_URL_BETA];
[manager POST:webService parameters:myDict1 constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
[formData appendPartWithFileData:picturedata name:#"file" fileName:#"testvideo.mov" mimeType:#"video/quickTime"];
} progress:nil success:^(NSURLSessionDataTask * Nonnull task, id Nullable responseObject) {
if ([[NSString stringWithFormat:#"%#",[responseObject valueForKey: #"status"] ] isEqualToString:#"1"])
{
}
else
{
}
}
failure:^(NSURLSessionDataTask _Nullable task, NSError _Nonnull error) {
NSLog(#"Failure %#",error);
}];
}
Crash ScenarioI am using AFNetworking for GET and POST requests and I am calling GET and POST methods on MAIN QUEUE and when the response comes,I update the UI.Now,before the response comes from API I am pushing onto another ViewController,and that's when the crash occurs.The message says:bad_accessPossible SolutionShould I be calling that method on some background queue so that I Can update that on MAIN QUEUE.Is it correct? Here is the code:
-(void)getDataFromUrl:(NSString *)url withRequestName:(NSString *)requestName withMessege:(NSMutableDictionary *)message
{
Reachability* googleReach = [Reachability reachabilityWithHostName:#"www.google.com"];
if(googleReach.currentReachabilityStatus!=0)
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"output :%#", responseObject);
arrayParsedJson = (NSMutableArray * )responseObject;
[self.delegate dataReceivedFromService:arrayParsedJson withRequestName:requestName];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self.delegate dataReceivedErrorService:error withRequestName:requestName withMsg:error.description];
}];
}
else
{
//[TSMessage showNotificationInViewController:views title:Title_Alert subtitle:Service_Alert type:TSMessageNotificationTypeError];
}
}
So when I get response in the success block,I call my delegate methods you can see.But if I have navigated to some other viewController before the response comes in block, it crashes.
I implemented this in my GatewayManager.m
+ (void)GetAPIName:(NSString *)APIName
withParameter:(NSMutableDictionary *)parameter
returnManager:(void(^)(AFHTTPSessionManager *manager))returnManager
progress:(void(^)(NSProgress *uploadProgress))progress
success:(void(^)(NSDictionary *result))success
error:(void(^)(NSError *error))failure {
if([ShareFunction isInternetConnecting] && [ShareFunction isVPNConnected]) {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *urlString = [NSString stringWithFormat:#"%#%#", kServerDomain, APIName];
if (![APIName isEqualToString:kAccountLogin]) {
[parameter setObject:[UserManager shareInstance].token forKey:#"accessToken"];
}
[manager GET:urlString
parameters:parameter
progress:^(NSProgress * _Nonnull downloadProgress) {
progress(downloadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"[API] %# Success : %#",APIName, responseObject);
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"[API] %# Error : %#",APIName, error);
failure(error);
//NSLog(#"[API] %# Error : %#",APIName, error);
}];
} else {
[ShareFunction showSimpleAlertWithString:#"Internet/VPN no connect" inVC:[UIApplication sharedApplication].keyWindow.rootViewController];
failure(nil);
}
}
I have a problem with this line
[ShareFunction showSimpleAlertWithString:#"Internet/VPN no connect" inVC:[UIApplication sharedApplication].keyWindow.rootViewController];
If it's root VC who calls this method, there's no problem to show the alert message on that VC. But if it's not root VC, how can I show the alert message on that VC?
Just replace this
[ShareFunction showSimpleAlertWithString:#"Internet/VPN no connect" inVC:[UIApplication sharedApplication].keyWindow.rootViewController];
with
[ShareFunction showSimpleAlertWithString:#"Internet/VPN no connect"];
I used the web Service in AppDelegate. But i want to show the SVProgressHUD on the initial view controller (View Controller), And when the Web Service completed then hide the SVProgressHUD in View Controller.
There is a static method on SVProgressHUD called
+ (void)setContainerView:(UIView*)containerView;
[SVProgressHUD setContainerView:yourViewController.view];
I understand your demand, my suggestion is to package two
class,HUD and Mysevers:
I have token example here:
HUD.m:
#import "HUD.h"
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#implementation HUD
+(void)addHUD
{
MBProgressHUD* HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
HUD.tag = 5000;
HUD.labelText = #"正在加载";
[WINDOW addSubview:HUD];
[HUD show:YES];
}
+(void)removeHUD
{
MBProgressHUD* HUD = (MBProgressHUD*)[WINDOW viewWithTag:5000];
[HUD removeFromSuperview];
HUD = nil;
}
#end
Mysevers.m:
#import "Mysevers.h"
#import "AFNetworking.h"
#import "HUD.h"
#implementation Mysevers
+(void)AFPOSTAddressname:(NSString*)addressName parmas:(NSDictionary*)parmas RequestSuccess:(void(^)(id result))success failBlcok:(void(^)(void))failBlcok{
[HUD addHUD];
AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];
NSString *urlStr = [NSString stringWithFormat:#"%#%#",BASE_URL,addressName];
NSLog(#"%#",urlStr);
/*[requestManager POST:urlStr parameters:parmas success:^(NSURLSessionTask *task, id responseObject) {
[HUD removeHUD];
success(responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"error==%#",[error localizedDescription]);
[HUD removeHUD];
failBlcok();
}];*/
[requestManager POST:urlStr parameters:parmas progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[HUD removeHUD];
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (error != nil) {
NSLog(#"error==%#",[error localizedDescription]);
[HUD removeHUD];
failBlcok();
}
return ;
}];
}
+(void)AFGETAddressname:(NSString*)addressName parmas:(NSDictionary*)parmas RequestSuccess:(void(^)(id result))success failBlcok:(void(^)(void))failBlcok{
[HUD addHUD];
AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];
NSString *urlStr = [NSString stringWithFormat:#"%#%#",BASE_URL,addressName];
NSLog(#"%#",urlStr);
/*[requestManager GET:urlStr parameters:parmas success:^(NSURLSessionTask *task, id responseObject) {
[HUD removeHUD];
success(responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"error==%#",[error localizedDescription]);
[HUD removeHUD];
failBlcok();
}];*/
[requestManager GET:urlStr parameters:parmas progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[HUD removeHUD];
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error==%#",[error localizedDescription]);
[HUD removeHUD];
failBlcok();
}];
}
#end
USAGE
You can have a test in your project:
[Mysevers AFPOSTAddressname:url parmas:params RequestSuccess:^(id result) {
// code here
}
Hope this can help you, this is my experience.And if you want to use SVProgressHUD, you can also replace the MBProgressHUD.
Since I am new to IOS and AFNetworking 3,0 is new, I don't know how to retrieve data from AFHTTPSessionManager.
I have to following message and I want to return the result
- (NSString *) makeServiceCall;
{
NSString *response = #"";
#try {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
POST:self.url.absoluteString
parameters:self.parameters
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Success: %#", responseObject);}
failure:^(NSURLSessionDataTask * task, NSError * error) {
NSLog(#"Error: %#", error);
}];
[AFHTTPSessionManager manager].securityPolicy.allowInvalidCertificates = YES;
}
#catch (NSException *exception) {
NSLog(#"%#", exception.reason);
}
}
The method AFHTTPSessionManager POST:parameters:progress:success:failure: is an asynchronous method.
What you are trying to do is return a string from the method calling it. This will not work as the method will finish before the download has started.
You need to call this with a completion block something like this...
- (void)getStringWithCompletionHandler:(void (^)(id))completion {
NSLog(#"Method started");
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
POST:self.url.absoluteString
parameters:self.parameters
progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Download underway");
}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Download successful");
completion(responseObject);
}
failure:^(NSURLSessionDataTask * task, NSError * error) {
NSLog(#"Error");
}];
// trying to return a string here won't work because the download hasn't finished yet.
// You can see the order of things happening by adding logs...
NSLog(#"Method finished");
}
The order of the logs in this code will be...
Method started
Method finished
Download underway
Download successful
As you can see, trying to return at the end of the method won't work because the download won't have completed yet.