Created
December 7, 2017 10:41
-
-
Save flaviodsilverio/fe9c7c158c3920582c9ecdf58d6be310 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void) URLRequestObjCParaOCDN { | |
//descomenta isto ---> //__weak "nomeDaClasseOndeTensIsto" *weakSelf = self; //nao uses self. em lado nenhum no block, usa weakSelf. nao pode originar leaks e é igual #proTip | |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"o teu link aqui"]]; | |
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler: | |
^(NSData *data, NSURLResponse *response, NSError *error) { | |
//Ele so executa isto quando o request e finalizado, isto e executado numa background thread. Se aqui dentro precisares de usar um "self." diz-me que ensino-te a fazer um weakify ao self para nao teres um memory leak. O "error" so traz erros quando nao tens net e assim, o data é onde vem o json ou o erro do body, o response e onde veem os headers. | |
if (error == nil) { //isto assume que o request foi successfull a nivel de execucao, nao de integridade de dados | |
if ([response isKindOfClass:[NSHTTPURLResponse class]]) { //isto apanha http e nao ftp | |
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; | |
// do stuff | |
if([httpResponse statusCode] < 400){ //tudo quanto sejam erros e server issues fica no else | |
NSError *decryptionError; | |
id deserialised = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&decryptionError]; | |
if([[deserialised class] isSubclassOfClass:[NSArray class]]) { | |
//se a resposta vier em array | |
NSDictionary *responseArray = (NSDictionary *)deserialised; | |
} else if([[deserialised class] isSubclassOfClass:[NSDictionary class]]) { | |
//se a resposta for um dict | |
NSDictionary *responseDict = (NSDictionary *)deserialised; | |
} | |
//Se quiseres executar na main thread: | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
// o que aqui estiver mete na main thread, mas nao metas aqui nada de jsons e afins, deixa essas coisas em background | |
}); | |
} else { | |
} | |
} | |
} else { | |
} | |
}] resume]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment