ios - objective-c how to us NSURLSession with AFNetworking -
i have code here logins me url, issue when try remove creds not working, found solution online:
if you're using nsurlsession, invalidate session , create new one, e.g.: [self.session invalidateandcancel]; self.session = [nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration defaultsessionconfiguration] delegate:self delegatequeue:nil]; clear session-scoped credentials.
so question is, can use nsurlsession afnetworking:
nsurl *url = [nsurl urlwithstring:kip]; nsurlrequest *request = [nsurlrequest requestwithurl:url]; afhttprequestoperation *operation = [[afhttprequestoperation alloc] initwithrequest:request]; nsurlcredential *credential = [nsurlcredential credentialwithuser:user password:password persistence:nsurlcredentialpersistenceforsession]; [operation setcredential:credential]; [[nsoperationqueue mainqueue] addoperation:operation]; [operation setcompletionblockwithsuccess:^(afhttprequestoperation *operation, id responseobject) { if (completionhandler) { completionhandler(responseobject, nil); } } failure:^(afhttprequestoperation *operation, nserror *error) { if (completionhandler) { completionhandler(nil, error); } }]; [operation start];
update
i got started on this:
nsurl *url = [nsurl urlwithstring:kip]; nsurlsessionconfiguration *sessionconfiguration = [nsurlsessionconfiguration defaultsessionconfiguration]; afurlsessionmanager *manager = [[afurlsessionmanager alloc] initwithsessionconfiguration:sessionconfiguration]; [manager setresponseserializer:[afjsonresponseserializer serializer]]; nsurlrequest *request = [nsurlrequest requestwithurl:url]; [[manager datataskwithrequest:request completionhandler:^(nsurlresponse *response, id responseobject, nserror *error) { if (completionhandler) { completionhandler(responseobject, nil); } }] resume];
how add username , password this?
try using afnsurlsession instead of afhttprequestoperation. in afnsurlsession can supply block delegate setsessiondidreceiveauthenticationchallengeblock can provide necessary credential.
from afnsurlsession.h:
/** sets block executed when connection level authentication challenge has occurred, handled `nsurlsessiondelegate` method `urlsession:didreceivechallenge:completionhandler:`. @param block block object executed when connection level authentication challenge has occurred. block returns disposition of authentication challenge, , takes 3 arguments: session, authentication challenge, , pointer credential should used resolve challenge. */ - (void)setsessiondidreceiveauthenticationchallengeblock:(nsurlsessionauthchallengedisposition (^)(nsurlsession *session, nsurlauthenticationchallenge *challenge, nsurlcredential * __autoreleasing *credential))block;
Comments
Post a Comment