0

Hi, I want to read the file type from a downloaded file in iOS which does not have an extension.

Eg: http://somelink/2a3bc

Its a valid pdf file. When I download it gets downloaded as NSData stream at a url(NSURL). if I rename it to 2a3bc.pdf it can be previewed using UIDocumentInteractionController but when I open the url without extension it does not recognise it as file valid file. Its UTI becomes public.data

Is there any way I can read the file type from NSData and rename the file according to that and open it using UIDocumentInteractionController.

Regards, Nandu Ahmed

Clad Clad
  • 2,653
  • 1
  • 20
  • 32
  • Does the response header tell you the content-type ? – Wain Apr 02 '14 at 10:28
  • No, I have downloaded it using NSURLSessionDownloadTask. response header is not present – user3488871 Apr 02 '14 at 10:34
  • Post your code. BTW it's possible to get response headers - see http://stackoverflow.com/questions/19547897/nsurlsessiondownloadtaskdelegate-json-response – ElmoVanKielmo Apr 02 '14 at 10:48
  • Yeah, I am able to get the response now. How can I change the Content type to UTI or extension. Any method available to convert content type to UTI or extension – user3488871 Apr 02 '14 at 11:02
  • Thanks, I am able to read the file properties `NSString *suggestedFileName = [downloadTask.response suggestedFilename]; CFStringRef mimeType = (CFStringRef)ContentTypeKey; CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL); CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);` – user3488871 Apr 02 '14 at 11:18

1 Answers1

1

Your download task has a link to the NSURLResponse *response that was received as part of the download. This contains the MIMEType that was set for the download. You should use that to determine what the file type is.

Technically you could read the first few bytes of data in the downloaded file but you would need a good amount of code to compare and identify all of the byte sequences...

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Thanks, but the response is `nil` in my case. – user3488871 Apr 02 '14 at 10:41
  • I do not get the MIME type in response ` { URL: https://abc/def/v1.1/files/filename } { status code: 200, headers { Connection = "Keep-Alive"; "Content-Length" = 136247; "Content-Type" = "application/zip"; Date = "Wed, 02 Apr 2014 10:43:26 GMT"; "Keep-Alive" = "timeout=120, max=500"; } }` – user3488871 Apr 02 '14 at 10:45
  • So you do have it and it says the data type is `zip`. So, if all come in as `zip` you need to have some other information from the server (like a good file name) or to analyse the file bytes (you will need to source info to match bytes). – Wain Apr 02 '14 at 10:54