###前提・実現したいこと
NSUrlを指定して、そこからテキストデータをダウンロードしたいんですが,上手くいかずに困っています。
###発生している問題・エラーメッセージ
サーバー上のデータの受信ができない
アプリを起動すると”ダウンロードが失敗しました”とでます
###該当のソースコード
swift
1import UIKit 2 3class ViewController: UIViewController,NSURLSessionDownloadDelegate{ 4 var str = NSString() 5 var button = UIButton() 6 var text = UITextView() 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 button.frame = CGRectMake(0, 0, 300, 100) 11 text.frame = CGRectMake(0, 0, 300, 300) 12 13 text.layer.position = CGPoint(x: self.view.frame.width/2, y: 300) 14 button.layer.position = CGPoint(x: self.view.frame.width/2, y: 100) 15 16 text.backgroundColor = UIColor.magentaColor() 17 button.backgroundColor = UIColor.cyanColor() 18 19 self.view.addSubview(text) 20 self.view.addSubview(button) 21 22 button.addTarget(self, action: #selector(self.btnpush), forControlEvents: .TouchUpInside) 23 super.viewDidLoad() 24 // 通信のコンフィグを用意. 25 let myConfig:NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession") 26 27 // Sessionを作成する. 28 let mySession:NSURLSession = NSURLSession(configuration: myConfig, delegate: self, delegateQueue: nil) 29 30 // ダウンロード先のURLからリクエストを生成. 31 let myURL:NSURL = NSURL(string: "http://npaka/iphone/test.txt")! 32 let myRequest:NSURLRequest = NSURLRequest(URL: myURL) 33 34 // ダウンロードタスクを生成. 35 let myTask:NSURLSessionDownloadTask = mySession.downloadTaskWithRequest(myRequest) 36 37 // タスクを実行. 38 myTask.resume() 39 } 40 41 /* 42 ダウンロード終了時に呼び出されるデリゲート. 43 */ 44 func btnpush(){ 45 _ = str.dataUsingEncoding(NSUTF8StringEncoding) 46 text.text = str as String 47 48 } 49 50 func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 51 52 do{ 53 _ = try NSData(contentsOfURL: location,options: NSDataReadingOptions.DataReadingMappedAlways)} 54 catch _ as NSError { 55 print("error") 56 } 57 58 } 59 60 /* 61 タスク終了時に呼び出されるデリゲート. 62 */ 63 func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { 64 65 if error == nil { 66 print("ダウンロードが完了しました") 67 } else { 68 print("ダウンロードが失敗しました") 69 } 70 71 72 } 73 override func didReceiveMemoryWarning() { 74 super.didReceiveMemoryWarning() 75 76 } 77}
###試したこと
ネットで調べてエラーを消すことはできたんですがデータを受信することができません
###補足情報(言語/FW/ツール等のバージョンなど)
swift2です。
print("ダウンロードが失敗しました")の後に、print(error)って入れてみたらどうですか