我是Objective-C的新手,我想从網路上下載檔案(如果已在網路服務器上进行了更改)並儲存在本地,以便我的應用程式可以使用它。
主要我想實現什麼
wget --timestamp <url>
做.
最新回復
- 5月前1 #
- 5月前2 #
NSURLSession是推荐的下載檔案的SDK方法.無需匯入第三方庫.
NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"]; NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url]; NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest]; [self.downloadTask resume];
然後,您可以使用NSURLSessionDownloadDelegate委託方法来监视錯誤,下載完成,下載进度等。如果您愿意,也可以使用內聯塊完成處理程式回撥方法.苹果文件說明了何時需要使用另一種.
已阅讀以下文章:
objc.io NSURLConnection到NSURLSession
URL載入系統程式設計指南
- 5月前3 #
我会使用 asynchronous 使用完成塊进行訪問。
此示例將Google徽標儲存到設備的文件目錄中. (iOS 5以上版本,OSX 10.7以上版本)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { NSLog(@"Download Error:%@",error.description); } if (data) { [data writeToFile:filePath atomically:YES]; NSLog(@"File is saved to %@",filePath); } }];
- 5月前4 #
我认為一種更簡單的方法是使用ASIHTTPRequest.三行代碼可以完成此任務:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDownloadDestinationPath:@"/path/to/my_file.txt"]; [request startSynchronous];
參考鏈接
UPDATE :我應该提到ASIHTTPRequest不再維護.作者特別建議人们改用其他框架,例如AFNetworking
- 5月前5 #
有時,我實現了一个易於使用的"下載管理器"庫:PTDownloadManager.你可以試一試!
相似問題
- iphone:如何在iOS的MKAnnotation中添加更多详细資訊iphoneobjectiveciosmkannotation2021-01-12 01:29
- objective c:iOS:一般从NSObject類序列化/反序列化複雜的JSONiosobjectivecjsongenericsjsonkit2021-01-10 17:56
- iphone:iOS應用程式Display Recorder如何在不使用私有API的情况下記錄螢幕?iphoneobjectivecios2021-01-09 22:31
- ios:設置UILabel行距iosobjectivecuilabelmultilinelinespacing2021-01-10 00:29
- ios:仪器分配跟蹤使用者定義類的物件的分配和取消分配iosobjectivecxcodeinstruments2021-01-10 04:56
我不確定wget是什麼,但是要从網路上获取檔案並將其儲存在本地,可以使用NSData: