How to store a video/image file from a server in iPhone

后端 未结 2 1423
星月不相逢
星月不相逢 2021-01-07 12:43

I want to send a video/image from one iPhone to another iPhone via a Server. I have successfully sent the file to the server using HTTP POST. But the problem is I want to re

2条回答
  •  隐瞒了意图╮
    2021-01-07 13:02

    You use Post to post data to server successfully. Right? Now you can make an API for downloading image/video. When you finish getting data, put it in document folder of your app. About API, for simplest, just create a link to that file, then use NSURLConnection to download.

    Create a URL connection to download:

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:strFileUrl]]; //strFileURL is url of your video/image
    NSURLConnection *conection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease];
    [conec start];
    [request release];
    

    Get path of file to save data:

    strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strFileName];
    

    Your class must adopt 3 methods of NSURLConnectionDelegate protocol: (please read about Protocol and Delegate)

    - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        // create 
        [[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil];
        file = [[NSFileHandle fileHandleForUpdatingAtPath:strFilePath] retain];// read more about file handle
        if (file)   {
            [file seekToEndOfFile];
        }
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata
    {    
        //write each data received
        if( receivedata != nil){
            if (file)  { 
                [file seekToEndOfFile];
            } 
            [file writeData:receivedata]; 
        }
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
        //close file after finish getting data;
        [file closeFile];
    }
    
    - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        //do something when downloading failed
    }
    

    If you want to review you file, use a UIWebview to load it:

    NSURL *fileURL = [NSURL fileURLWithPath:strFilePath];
    [wvReview loadRequest:[NSURLRequest requestWithURL:fileURL]];
    

提交回复
热议问题