iPhone - NSData da URL di file locale
Domanda
Ho un oggetto NSURL
che mi dà il percorso di un file locale (nella cartella documenti). Voglio compilare un oggetto NSData
con il contenuto di questo file. Provato ad utilizzare dataWithContentsOfURL:
ma questo non riesce. So che il file esiste perché il SDK
iPhone restituisce il percorso.
Qualcuno può dirmi come posso ottenere un oggetto NSData
dal URL
di un file locale?
Grazie.
Soluzione
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
Altri suggerimenti
Per ottenere questo lavoro basta fare:
NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"search" withExtension:@"png"];
NSString*stringPath = [imgPath absoluteString]; //this is correct
//you can again use it in NSURL eg if you have async loading images and your mechanism
//uses only url like mine (but sometimes i need local files to load)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
UIImage *ready = [[[UIImage alloc] initWithData:data] autorelease];
Assicurati che il tuo URL locale inizia con "file: //" allora si dovrebbe solo fare questo:
NSData *fileData = [NSData dataWithContentsOfFile:fileURL.path];
Per swift3 ho trovato risposta da seguente indirizzo utile
(mi è stato sempre seguendo il sentiero, dopo l'acquisizione dell'immagine utilizzando plugin di PhoneGap
file: ///var/mobile/Containers/Data/Application/B64B06DE-7976-45CF-9BE2-661F0F309A06/tmp/abcded.jpg)
https://stackoverflow.com/a/41043447/6383908
se lascia videoURL = URL (stringa: urlString), lascia videodata = prova? Dati (contentsOf: videoURL) { // Aggiungere codice di Alamofire qui }