iOSNSURLSessionExample(HTTPGET,POST,BackgroundDownlads)
IniOSNSURLSessionExample,IhaveexplainedhowuseNSURLSessionAPItomakeHTTPrequests.NSURLSessionclassisintroducediniOS7andOSXv10.9.NSURLSessionisreplacementforNSURLConnectionandthisAPIgivesyourapptheabilitytoperformbackgrounddownloadswhenyourappisinbackground.
NSURLConnectioniOSNSURLSessionExample
LeftimagesexplainshowNSURLConnectionWorks,andrightimageexplainshowNSURLSessionworks.
Belowtopicsarecoveredinthistutorial.
1).SessionTypes
2).NSURLSessionTask&Delegates
3).HTTPGETandPOSTwithNSURLSessionDataTask
4).FileDownloadwithNSURLSessionDownloadTask
5).FileDownloadwhenappisinbackground
iOSNSURLSessionExampleSource
1).NSURLSESSIONSESSIONTYPES
NSURLSessionhasthreetypesofSessions.
a).Defaultsession:
Thesharedsessionusestheglobalsingletoncredential,cacheandcookiestorageobjects.Thiscanbeusedinplaceofexistingcodethatuses+[NSURLConnectionsendAsynchronousRequest:queue:completionHandler:]
b).Ephemeralsession
Anephemeralsessionhasnopersistentdiskstorageforcookies,cacheorcredentials,theyarestoredinRAMandpurgedautomaticallywhenthesessionisinvalided.
c).Backgroundsession
BackgroundsessionissimilartoDefaultsession,Butitcanbeusedtoperformnetworkingoperationsonbehalfofasuspendedapplication,withincertainconstraints.
//Defaultsession
+(NSURLSessionConfiguration)defaultSessionConfiguration;
//Ephemeral
+(NSURLSessionConfiguration)ephemeralSessionConfiguration;
//Background
+(NSURLSessionConfiguration)backgroundSessionConfiguration:(NSString)identifier;
2).NSURLSESSIONTASKSANDDELEGATES
BelowimageexplainstypesofNSURLSessionTasksandtheirhierarchy.
NSURLSessionTasks
Tasksarecreatedintwoways.Ifyouusethesystemprovideddelegatemethod,youmustprovideacompletionhandlerblockthatreturnsdatatoyourappwhenatransferfinishessuccessfullyorwithanerror.ifyouprovidecustomdelegateobjects,thetaskobjectscallthosedelegates’methodswithdataasitisreceivedfromtheserver
2.1).NSURLSessionDataTask
DatatasksexchangedatausingNSData.NSURLSessionDataTaskisnotsupportedinBackgroundSessions.
2.1.1)CreateDatataskwithsystemprovidedDelegatemethods.
/Createsadatataskwiththegivenrequest.Therequestmayhaveabodystream./
-(NSURLSessionDataTask)dataTaskWithRequest:(NSURLRequest)request;
/CreatesadatatasktoretrievethecontentsofthegivenURL./
-(NSURLSessionDataTask)dataTaskWithURL:(NSURL)url;
WhenyouareusingtheaboveAPI,youneedtoimplementNSURLSessionDataDelegatemethods.
/Thetaskhasreceivedaresponseandnofurthermessageswillbe
receiveduntilthecompletionblockiscalled.Thedisposition
allowsyoutocancelarequestortoturnadatataskintoa
downloadtask.Thisdelegatemessageisoptional-ifyoudonot
implementit,youcangettheresponseasapropertyofthetask.
/
-(void)URLSession:(NSURLSession)sessiondataTask:(NSURLSessionDataTask)dataTask
didReceiveResponse:(NSURLResponse)response
completionHandler:(void(^)(NSURLSessionResponseDispositiondisposition))completionHandler
{
completionHandler(NSURLSessionResponseAllow);
}
/Sentwhendataisavailableforthedelegatetoconsume.Itis
assumedthatthedelegatewillretainandnotcopythedata.As
thedatamaybedis-contiguous,youshoulduse
[NSDataenumerateByteRangesUsingBlock:]toaccessit.
/
-(void)URLSession:(NSURLSession)sessiondataTask:(NSURLSessionDataTask)dataTask
didReceiveData:(NSData)data
{
//data:responsefromtheserver.
}
2.1.2)CreateDatataskwithcustomDelegatemethods.
/
datataskconveniencemethods.Thesemethodscreatetasksthat
bypassthenormaldelegatecallsforresponseanddatadelivery,
andprovideasimplecancelableasynchronousinterfacetoreceiving
data.ErrorswillbereturnedintheNSURLErrorDomain,
see.Thedelegate,ifany,willstillbe
calledforauthenticationchallenges.
/
-(NSURLSessionDataTask)dataTaskWithRequest:(NSURLRequest)requestcompletionHandler:(void(^)(NSDatadata,NSURLResponseresponse,NSErrorerror))completionHandler;
-(NSURLSessionDataTask)dataTaskWithURL:(NSURL)urlcompletionHandler:(void(^)(NSDatadata,NSURLResponseresponse,NSErrorerror))completionHandler;
2.2).NSURLSessionDownloadTask
NSURLSessionDownloadTaskdirectlywritestheresponsedatatoatemporaryfile.Itsupportsbackgrounddownloadswhentheappisnotrunning.
2.2.1)CreateDownloadTaskwithsystemprovideddelegatemethods.
/Createsadownloadtaskwiththewww.baiyuewang.netgivenrequest./
-(NSURLSessionDownloadTask)downloadTaskWithRequest:(NSURLRequest)request;
/CreatesadownloadtasktodownloadthecontentsofthegivenURL./
-(NSURLSessionDownloadTask)downloadTaskWithURL:(NSURL)url;
/Createsadownloadtaskwiththeresumedata.Ifthedownloadcannotbesuccessfullyresumed,URLSession:task:didCompleteWithError:willbecalled./
-(NSURLSessionDownloadTask)downloadTaskWithResumeData:(NSData)resumeData;
IfyouareusingtheaboveAPI,YouneedtoimplementNSURLSessionDownloadDelegatemethods
/Sentwhenadownloadtaskthathascompletedadownload.Thedelegateshould
copyormovethefileatthegivenlocationtoanewlocationasitwillbe
removedwhenthedelegatemessagereturns.URLSession:task:didCompleteWithError:will
stillbecalled.
/
-(void)URLSession:(NSURLSession)sessiondownloadTask:(NSURLSessionDownloadTask)downloadTask
didFinishDownloadingToURL:(NSURL)location;
/Sentperiodicallytonotifythedelegateofdownloadprogress./
-(void)URLSession:(NSURLSession)sessiondownloadTask:(NSURLSessionDownloadTask)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
/Sentwhenadownloadhasbeenresumed.Ifadownloadfailedwithan
error,the-userInfodictionaryoftheerrorwillcontainan
NSURLSessionDownloadTaskResumeDatakey,whosevalueistheresume
data.
/
-(void)URLSession:(NSURLSession)sessiondownloadTask:(NSURLSessionDownloadTask)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes;
2.2.2)CreateDownloadTaskwithcustomdelegatemethods.
/
downloadtaskconveniencemethods.Whenadownloadsuccessfully
completes,theNSURLwillpointtoafilethatmustbereador
copiedduringtheinvocationofthecompletionroutine.Thefile
willberemovedautomatically.
/
-(NSURLSessionDownloadTask)downloadTaskWithRequest:(NSURLRequest)requestcompletionHandler:(void(^)(NSURLlocation,NSURLResponseresponse,NSErrorerror))completionHandler;
-(NSURLSessionDownloadTask)downloadTaskWithURL:(NSURL)urlcompletionHandler:(void(^)(NSURLlocation,NSURLResponseresponse,NSErrorerror))completionHandler;
-(NSURLSessionDownloadTask)downloadTaskWithResumeData:(NSData)resumeDatacompletionHandler:(void(^)(NSURLlocation,NSURLResponseresponse,NSErrorerror))completionHandler;
2.3).NSURLSessionUploadTask
UploadTasksendsdata/fileanditsupportsbackgrounduploadswhentheappisnotrunning.
2.3.1)CreateUploadtaskwithsystemprovideddelegatemethods.
/Createsanuploadtaskwiththegivenrequest.ThebodyoftherequestwillbecreatedfromthefilereferencedbyfileURL/
-(NSURLSessionUploadTask)uploadTaskWithRequest:(NSURLRequest)requestfromFile:(NSURL)fileURL;
/Createsanuploadtaskwiththegivenrequest.ThebodyoftherequestisprovidedfromthebodyData./
-(NSURLSessionUploadTask)uploadTaskWithRequest:(NSURLRequest)requestfromData:(NSData)bodyData;
/Createsanuploadtaskwiththegivenrequest.Thepreviouslysetbodystreamoftherequest(ifany)isignoredandtheURLSession:task:needNewBodyStream:delegatewillbecalledwhenthebodypayloadisrequired./
-(NSURLSessionUploadTask)uploadTaskWithStreamedRequest:(NSURLRequest)request;
IfyouareusingtheaboveAPI,youneedtoimplementbelowNSURLSessionTaskDelegatemethod.
Note:NSURLSessionUploadTaskisnothavinganyspecialdelegateclass.DelegatemethodisinNSURLSessionTaskDelegate
/Sentperiodicallytonotifythedelegateofuploadprogress.This
informationisalsoavailableaspropertiesofthetask.
/
-(void)URLSession:(NSURLSession)sessiontask:(NSURLSessionTask)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
2.3.2)CreateUploadTaskwithcustomdelegatemethods.
1
2
-(NSURLSessionUploadTask)uploadTaskWithRequest:(NSURLRequest)requestfromFile:(NSURL)fileURLcompletionHandler:(void(^)(NSDatadata,NSURLResponseresponse,NSErrorerror))completionHandler;
-(NSURLSessionUploadTask)uploadTaskWithRequest:(NSURLRequest)requestfromData:(NSData)bodyDatacompletionHandler:(void(^)(NSDatadata,NSURLResponseresponse,NSErrorerror))completionHandler;
3).HTTPGETANDPOSTWITHNSURLSESSIONDATATASK
Inthissection,IhaveexplainedhowtosendHTTPGET/POSTrequestsusingNSURLSessionDataTask.
YouneedtofollowthebelowstepsforNSURLSession.
a)CreateSessionConfiguration
b)CreateaNSURLSessionObject.
c)CreateaNSURLSessionTask(Data,DownloadorUpload)
d)Ifyouwanttousesystemdelegatemethods,youneedtoimplementtheminyourclass.
e)Startthetaskbycalling[resume]method.
3.1HTPGETwithCustomdelegatemethod.
-(void)sendHTTPGet
{
NSURLSessionConfigurationdefaultConfigObject=[NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSessiondefaultSession=[NSURLSessionsessionWithConfiguration:defaultConfigObjectdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
NSURLurl=[NSURLURLWithString:@"http://hayageek.com/"];
NSURLSessionDataTaskdataTask=[defaultSessiondataTaskWithURL:url
completionHandler:^(NSDatadata,NSURLResponseresponse,NSErrorerror){
if(error==nil)
{
NSStringtext=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"Data=%@",text);
}
}];
[dataTaskresume];
}
3.2).HTTPPOSTwithCustomdelegatemethod.
-(void)httpPostWithCustomDelegate
{
NSURLSessionConfigurationdefaultConfigObject=[NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSessiondefaultSession=[NSURLSessionsessionWithConfiguration:defaultConfigObjectdelegate:nildelegateQueue:[NSOperationQueuemainQueue]];
NSURLurl=[NSURLURLWithString:@"http://hayageek.com/examples/jquery/ajax-post/ajax-post.php"];
NSMutableURLRequesturlRequest=[NSMutableURLRequestrequestWithURL:url];
NSStringparams=@"name=Ravi&loc=India&age=31&submit=true";
[urlRequestsetHTTPMethod:@"POST"];
[urlRequestsetHTTPBody:[paramsdataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTaskdataTask=[defaultSessiondataTaskWithRequest:urlRequest
completionHandler:^(NSDatadata,NSURLResponseresponse,NSErrorerror){
NSLog(@"Response:%@%@\n",response,error);
if(error==nil)
{
NSStringtext=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"Data=%@",text);
}
}];
[dataTaskresume];
}
3.3).HTTPPOSTwithsystemprovideddelegatemethods.
Whenyouwantusesystemprovideddelegatemethods,youneedtoimplementNSURLSessionDataDelegatemethods.
-(void)URLSession:(NSURLSession)sessiondataTask:(NSURLSessionDataTask)dataTask
didReceiveResponse:(NSURLResponse)response
completionHandler:(void(^)(NSURLSessionResponseDispositiondisposition))completionHandler
{
NSLog(@"###handler1");
completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession)sessiondataTask:(NSURLSessionDataTask)dataTask
didReceiveData:(NSData)data
{
NSStringstr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"ReceivedString%@",str);
}
-(void)URLSession:(NSURLSession)sessiontask:(NSURLSessionTask)task
didCompleteWithError:(NSError)error
{
if(error==nil)
{
NSLog(@"DownloadisSuccesfull");
}
else
NSLog(@"Error%@",[erroruserInfo]);
}
BelowisthecodeforsendingHTTPPostRequest.
-(void)sendHTTPPost
{
NSURLSessionConfigurationdefaultConfigObject=[NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSessiondefaultSession=[NSURLSessionsessionWithConfiguration:defaultConfigObjectdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
NSURLurl=[NSURLURLWithString:@"http://hayageek.com/examples/jquery/ajax-post/ajax-post.php"];
NSMutableURLRequesturlRequest=[NSMutableURLRequestrequestWithURL:url];
NSStringparams=@"name=Ravi&loc=India&age=31&submit=true";
[urlRequestsetHTTPMethod:@"POST"];
[urlRequestsetHTTPBody:[paramsdataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTaskdataTask=[defaultSessiondataTaskWithRequest:urlRequest];
[dataTaskresume];
}
4).FILEDOWNLOADWITHNSURLSESSIONDOWNLOADTASK
Inthissection,IhaveexplainedhowtodownloadfilesusingNSURLSessionDownloadTask.
4.1).FileDownloadwithcustomdelegatemethod.
-(void)downloadFile
{
NSURLurl=[NSURLURLWithString:@"https://s3.amazonaws.com/hayageek/downloads/SimpleBackgroundFetch.zip"];
NSURLSessionConfigurationdefaultConfigObject=[NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSessiondefaultSession=[NSURLSessionsessionWithConfiguration:defaultConfigObjectdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
NSURLSessionDownloadTaskdownloadTask=[defaultSessiondownloadTaskWithURL:url
completionHandler:^(NSURLlocation,NSURLResponseresponse,NSErrorerror)
{
if(error==nil)
{
NSLog(@"Temporaryfile=%@",location);
NSErrorerr=nil;
NSFileManagerfileManager=[NSFileManagerdefaultManager];
NSStringdocsDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
NSURLdocsDirURL=[NSURLfileURLWithPath:[docsDirstringByAppendingPathComponent:@"out.zip"]];
if([fileManagermoveItemAtURL:location
toURL:docsDirURL
error:&err])
{
NSLog(@"Fileissavedto=%@",docsDir);
}
else
{
NSLog(@"failedtomove:%@",[erruserInfo]);
}
}
}];
[downloadTaskresume];
}
Ifyouwanttogetdownloadprogressyouneedtousesystemprovideddelegatemethods.
4.1).FileDownloadwithsystemprovideddelegatemethod.
YouneedtoimplementNSURLSessionDownloadDelegatemethods.
27
-(void)URLSession:(NSURLSession)sessiondownloadTask:(NSURLSessionDownloadTask)downloadTaskdidFinishDownloadingToURL:(NSURL)location
{
NSLog(@"TemporaryFile:%@\n",location);
NSErrorerr=nil;
NSFileManagerfileManager=[NSFileManagerdefaultManager];
NSStringdocsDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
NSURLdocsDirURL=[NSURLfileURLWithPath:[docsDirstringByAppendingPathComponent:@"out1.zip"]];
if([fileManagermoveItemAtURL:location
toURL:docsDirURL
error:&err])
{
NSLog(@"Fileissavedto=%@",docsDir);
}
else
{
NSLog(@"failedtomove:%@",[erruserInfo]);
}
}
-(void)URLSession:(NSURLSession)sessiondownloadTask:(NSURLSessionDownloadTask)downloadTaskdidWriteData:(int64_t)bytesWrittentotalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//Youcangetprogresshere
NSLog(@"Received:%lldbytes(Downloaded:%lldbytes)Expected:%lldbytes.\n",
bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
}
Belowcodedownloadsthefile.
-(void)downloadFileWithProgress
{
NSURLurl=[NSURLURLWithString:@"https://s3.amazonaws.com/hayageek/downloads/SimpleBackgroundFetch.zip"];
NSURLSessionConfigurationdefaultConfigObject=[NSURLSessionConfigurationdefaultSessionConfiguration];
NSURLSessiondefaultSession=[NSURLSessionsessionWithConfiguration:defaultConfigObjectdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
NSURLSessionDownloadTaskdownloadTask=[defaultSessiondownloadTaskWithURL:url];
[downloadTaskresume];
}
5).FILEDOWNLOADWHENAPPISINBACKGROUND
Todownloaddatawhentheappisinbackground,youneedtouseNSURLSession’sbackgroundsession.Belowcodeexplainshowtocreatebackgroundtask.
-(void)backgroundDownloadTask
{
NSURLurl=[NSURLURLWithString:@"http://www.hdwallpapersinn.com/wp-content/uploads/2012/09/HD-Wallpaper-1920x1080.jpg"];
NSURLSessionConfigurationbackgroundConfig=[NSURLSessionConfigurationbackgroundSessionConfiguration:@"backgroundtask1"];
NSURLSessionbackgroundSeesion=[NSURLSessionsessionWithConfiguration:backgroundConfigdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
NSURLSessionDownloadTaskdownloadTask=[backgroundSeesiondownloadTaskWithURL:url];
[downloadTaskresume];
}
IniOS,whenabackgroundtransfercompletes,iOSrelaunchesyourappinthebackgroundandcallstheapplication:handleEventsForBackgroundURLSession:completionHandler:methodonyourapp’sUIApplicationDelegateobject.YouneedtostorethatcompletionHandler.Youcanusetheargumentidentifiertorejointhebackgroundsession.
whenthesessionfinishesthelastbackgrounddownloadtask,itsendsthesessiondelegateaURLSessionDidFinishwww.wang027.comEventsForBackgroundURLSession:message.Yoursessiondelegateshouldthencallthestoredcompletionhandler.
1).AddhandleEventsForBackgroundURLSession()delegatemethodinyourAppDelegateclass.
-(void)application:(UIApplication)applicationhandleEventsForBackgroundURLSession:(NSString)identifiercompletionHandler:(void(^)())completionHandler
NSLog(@"SavecompletionHandler");self.completionHandler=completionHandler;
}
2).addURLSessionDidFinishEventsForBackgroundURLSession()delegateinNSURLSessionDelegateclass.
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession)session
{
NSLog(@"BackgroundURLsession%@finishedevents.\n",session);
AppDelegatedelegate=(AppDelegate)[[UIApplicationsharedApplication]delegate];
if(delegate.completionHandler)
{
void(^handler)()=delegate.completionHandler;
handler();
}
}
Reference:AppleDocumentation
|
|