teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

7

コード編集

2017/07/07 03:19

投稿

fujico23
fujico23

スコア13

title CHANGED
File without changes
body CHANGED
@@ -12,9 +12,6 @@
12
12
 
13
13
  ###該当のソースコード
14
14
  ```Swift
15
-
16
-
17
- func tappedSentToServerButton(_ sender: UIButton) {
18
15
 
19
16
  let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
20
17
 
@@ -31,20 +28,7 @@
31
28
  var datas: [NSData] = try url(contentsOfFile: documentPath + "/" + fileName, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)).lines
32
29
  datas = datas.deleteSpaceOnly(datas: datas)
33
30
  return datas
34
-
35
- let myConfig: URLSessionConfiguration = URLSessionConfiguration.default
36
- let url: NSURL = NSURL(string: "http://***.php")
37
- var request: URLRequest = URLRequest(url: url as URL)
38
- request.httpMethod = "POST"
39
- let session: URLSession = URLSession(configuration: myConfig, delegate: self, delegateQueue: OperationQueue.main)
40
- let task: URLSessionUploadTask = session.uploadTask(with: request, from: datas as Data)
41
-
42
- task.resume()
43
- } catch {
44
- return nil
45
- }
46
31
  }
47
- }
48
32
 
49
33
 
50
34
  ```

6

コードの編集

2017/07/07 03:18

投稿

fujico23
fujico23

スコア13

title CHANGED
File without changes
body CHANGED
@@ -12,174 +12,8 @@
12
12
 
13
13
  ###該当のソースコード
14
14
  ```Swift
15
- import UIKit
16
- import AVFoundation
17
15
 
18
- class ViewController: UIViewController, UIGestureRecognizerDelegate, URLSessionTaskDelegate {
19
- var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
20
- var mySession : AVCaptureSession!
21
- var myDevice : AVCaptureDevice
22
- var myImageOutput: AVCaptureStillImageOutput!
23
- var myTimer = Timer()
24
- var second: Int = 30
25
- let SentToServerButton = UIButton()
26
- let playButton = UIButton()
27
-
28
- override func viewDidLoad() {
29
- super.viewDidLoad()
30
- let fileManager = FileManager.default
31
- do {
32
- let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
33
- if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
34
- while let fileURL = enumerator.nextObject() as? URL {
35
- try fileManager.removeItem(at: fileURL)
36
- }
37
- }
38
- } catch {
39
- print("削除に失敗 \n \(error)")
40
- }
41
- mySession = AVCaptureSession()
42
- mySession.sessionPreset = AVCaptureSessionPresetHigh
43
- let devices = AVCaptureDevice.devices()
44
- for device in devices! {
45
- if((device as AnyObject).position == AVCaptureDevicePosition.back){
46
- myDevice = device as! AVCaptureDevice
47
- }
48
- }
49
- let videoInput = try! AVCaptureDeviceInput.init(device: myDevice)
50
- mySession.addInput(videoInput)
51
- myImageOutput = AVCaptureStillImageOutput()
52
- myImageOutput.outputSettings = [ kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA ]
53
- mySession.addOutput(myImageOutput)
54
- for connection in myImageOutput.connections {
55
- if let conn = connection as? AVCaptureConnection {
56
- if conn.isVideoOrientationSupported {
57
- conn.videoOrientation = AVCaptureVideoOrientation.portrait
58
- }
59
- }
60
- }
61
- let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
62
- myVideoLayer?.frame = self.view.bounds
63
- myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
64
- self.view.layer.addSublayer(myVideoLayer!)
65
- mySession.startRunning()
66
- let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedScreen))
67
- tapGesture.delegate = self
68
- self.view.addGestureRecognizer(tapGesture)
69
- playButton.setTitle("撮影開始", for: .normal)
70
- playButton.frame = CGRect(x: 120, y: 450, width: 80, height: 80)
71
- playButton.setTitleColor(UIColor.black, for: UIControlState())
72
- playButton.layer.position = CGPoint(x: view.frame.width / 2, y: self.view.bounds.size.height - 80)
73
- playButton.backgroundColor = UIColor.red
74
- playButton.addTarget(self, action: #selector(ViewController.tappedPlayButton), for: .touchUpInside)
75
- self.view.addSubview(playButton)
76
-
77
- SentToServerButton.setTitle("サーバに送付", for: .normal)
78
- SentToServerButton.contentMode = .scaleAspectFit
79
- SentToServerButton.frame = CGRect(x: 300, y: 200, width: 120, height: 50)
80
- SentToServerButton.backgroundColor = UIColor.black
81
- SentToServerButton.setTitleColor(UIColor.white, for: UIControlState())
82
- SentToServerButton.layer.position = CGPoint(x: view.frame.width / 2 + 80, y: self.view.bounds.size.height - 300)
83
- SentToServerButton.addTarget(self, action: #selector(ViewController.tappedSentToServerButton), for: .touchUpInside)
84
- view.addSubview(SentToServerButton)
85
- }
86
-
87
16
 
88
- func tappedPlayButton(sender: UIButton) {
89
-
90
- print("start!")
91
-
92
- playButton.isHidden = true
93
-
94
- second = 30
95
-
96
- myTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.TemporalEvent), userInfo: nil, repeats: true)
97
-
98
-
99
- }
100
-
101
-
102
- func TemporalEvent(){
103
-
104
-
105
- second -= 3
106
-
107
- captureStillImage()
108
- if second == 0 {
109
- myTimer.invalidate()
110
- }
111
- }
112
-
113
- func captureStillImage() {
114
-
115
- if let output = myImageOutput {
116
-
117
- DispatchQueue.global().async {
118
-
119
- let connection = output.connection(withMediaType: AVMediaTypeVideo)
120
-
121
- let settings = [-1.0, 0.0, 2.5].map {
122
- (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
123
- AVCaptureAutoExposureBracketedStillImageSettings.autoExposureSettings(withExposureTargetBias: bias)
124
- }
125
-
126
- output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
127
- if error == nil {
128
-
129
-
130
- let image = self.imageFromImageBuffer(imageBuffer!)
131
- let JPEGdata = UIImageJPEGRepresentation(image!, 1)
132
-
133
- let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
134
- print("書き込むファイルのパス: \(fileURL)")
135
-
136
- do {
137
- try JPEGdata?.write(to: fileURL, options: .atomic)
138
- } catch {
139
- print("保存に失敗:\(error)")
140
- }
141
- } else {
142
- print("JPEG取得に失敗:\(error)")
143
- }
144
- })
145
- }
146
- }
147
- }
148
-
149
- // imageBufferからUIImageに変換.
150
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
151
-
152
- if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
153
-
154
- CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
155
-
156
- let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
157
- let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
158
- let width = CVPixelBufferGetWidth(imageBuffer)
159
- let height = CVPixelBufferGetHeight(imageBuffer)
160
- let colorSpace = CGColorSpaceCreateDeviceRGB()
161
-
162
- guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
163
-
164
- print("Couldn't create context for image.")
165
- return nil
166
- }
167
-
168
- let quartzImage = context.makeImage()
169
-
170
- CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
171
-
172
- if let quartzImage = quartzImage {
173
-
174
- // UIImage.
175
- let image = UIImage(cgImage: quartzImage)
176
-
177
- return image
178
- }
179
- }
180
- return nil
181
- }
182
-
183
17
  func tappedSentToServerButton(_ sender: UIButton) {
184
18
 
185
19
  let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
@@ -212,9 +46,5 @@
212
46
  }
213
47
  }
214
48
 
215
- override func didReceiveMemoryWarning() {
49
+
216
- super.didReceiveMemoryWarning()
217
- // Dispose of any resources that can be recreated.
218
- }
219
- }
220
50
  ```

5

コードの編集

2017/07/07 00:56

投稿

fujico23
fujico23

スコア13

title CHANGED
File without changes
body CHANGED
@@ -1,55 +1,138 @@
1
1
  ###前提・実現したいこと
2
2
  iPhone cameraで撮影したSampleBufferをJPEGに変え、Directoryに保存し、一括でPOST通信するアプリを作成しています。
3
3
  写真はTimer関数を用いて複数枚とっています。
4
- 実機シミュレーションで、ビルドは通りますが、POST送信するところで以下のエラーが出てしまいます。
4
+ 実機シミュレーションで、以下のエラーが出てしまいます。
5
- サーバに送付するところのコードがどこか間違っているのだと思いますが、ご教示頂ければ幸いです。
5
+ ご教示頂ければ幸いです。
6
6
 
7
- よろしくお願いいたします。
8
-
9
7
  ###発生している問題・エラーメッセージ
10
8
 
11
9
  ```
12
- Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton copyWithZone:]: unrecognized selector sent to instance 0x14da0890'
10
+ 'flatMap' produces '[SegmentOfResult.Iterator.Element]', not the expected contextual result type '()'
13
-
14
- libc++abi.dylib: terminating with uncaught exception of type NSException
15
11
  ```
16
12
 
17
13
  ###該当のソースコード
18
14
  ```Swift
19
- /*
15
+ import UIKit
20
- 撮影
21
- */
22
- // 撮影する関数.
16
+ import AVFoundation
17
+
18
+ class ViewController: UIViewController, UIGestureRecognizerDelegate, URLSessionTaskDelegate {
19
+ var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
20
+ var mySession : AVCaptureSession!
21
+ var myDevice : AVCaptureDevice
22
+ var myImageOutput: AVCaptureStillImageOutput!
23
+ var myTimer = Timer()
24
+ var second: Int = 30
25
+ let SentToServerButton = UIButton()
26
+ let playButton = UIButton()
27
+
28
+ override func viewDidLoad() {
29
+ super.viewDidLoad()
30
+ let fileManager = FileManager.default
31
+ do {
32
+ let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
33
+ if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
34
+ while let fileURL = enumerator.nextObject() as? URL {
35
+ try fileManager.removeItem(at: fileURL)
36
+ }
37
+ }
38
+ } catch {
39
+ print("削除に失敗 \n \(error)")
40
+ }
41
+ mySession = AVCaptureSession()
42
+ mySession.sessionPreset = AVCaptureSessionPresetHigh
43
+ let devices = AVCaptureDevice.devices()
44
+ for device in devices! {
45
+ if((device as AnyObject).position == AVCaptureDevicePosition.back){
46
+ myDevice = device as! AVCaptureDevice
47
+ }
48
+ }
49
+ let videoInput = try! AVCaptureDeviceInput.init(device: myDevice)
50
+ mySession.addInput(videoInput)
51
+ myImageOutput = AVCaptureStillImageOutput()
52
+ myImageOutput.outputSettings = [ kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA ]
53
+ mySession.addOutput(myImageOutput)
54
+ for connection in myImageOutput.connections {
55
+ if let conn = connection as? AVCaptureConnection {
56
+ if conn.isVideoOrientationSupported {
57
+ conn.videoOrientation = AVCaptureVideoOrientation.portrait
58
+ }
59
+ }
60
+ }
61
+ let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
62
+ myVideoLayer?.frame = self.view.bounds
63
+ myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
64
+ self.view.layer.addSublayer(myVideoLayer!)
65
+ mySession.startRunning()
66
+ let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedScreen))
67
+ tapGesture.delegate = self
68
+ self.view.addGestureRecognizer(tapGesture)
69
+ playButton.setTitle("撮影開始", for: .normal)
70
+ playButton.frame = CGRect(x: 120, y: 450, width: 80, height: 80)
71
+ playButton.setTitleColor(UIColor.black, for: UIControlState())
72
+ playButton.layer.position = CGPoint(x: view.frame.width / 2, y: self.view.bounds.size.height - 80)
73
+ playButton.backgroundColor = UIColor.red
74
+ playButton.addTarget(self, action: #selector(ViewController.tappedPlayButton), for: .touchUpInside)
75
+ self.view.addSubview(playButton)
76
+
77
+ SentToServerButton.setTitle("サーバに送付", for: .normal)
78
+ SentToServerButton.contentMode = .scaleAspectFit
79
+ SentToServerButton.frame = CGRect(x: 300, y: 200, width: 120, height: 50)
80
+ SentToServerButton.backgroundColor = UIColor.black
81
+ SentToServerButton.setTitleColor(UIColor.white, for: UIControlState())
82
+ SentToServerButton.layer.position = CGPoint(x: view.frame.width / 2 + 80, y: self.view.bounds.size.height - 300)
83
+ SentToServerButton.addTarget(self, action: #selector(ViewController.tappedSentToServerButton), for: .touchUpInside)
84
+ view.addSubview(SentToServerButton)
85
+ }
86
+
87
+
88
+ func tappedPlayButton(sender: UIButton) {
89
+
90
+ print("start!")
91
+
92
+ playButton.isHidden = true
93
+
94
+ second = 30
95
+
96
+ myTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.TemporalEvent), userInfo: nil, repeats: true)
97
+
98
+
99
+ }
100
+
101
+
102
+ func TemporalEvent(){
103
+
104
+
105
+ second -= 3
106
+
107
+ captureStillImage()
108
+ if second == 0 {
109
+ myTimer.invalidate()
110
+ }
111
+ }
112
+
23
113
  func captureStillImage() {
24
-
25
- // 出力先が正しいことを確認.
114
+
26
115
  if let output = myImageOutput {
27
-
28
- // キュー.
116
+
29
117
  DispatchQueue.global().async {
30
-
31
- // 撮影の設定.
118
+
32
119
  let connection = output.connection(withMediaType: AVMediaTypeVideo)
33
120
 
34
- // 撮影する露光時間を±2.0に設定.
35
- let settings = [-2.0, 0.0, 2.0].map {
121
+ let settings = [-1.0, 0.0, 2.5].map {
36
122
  (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
37
123
  AVCaptureAutoExposureBracketedStillImageSettings.autoExposureSettings(withExposureTargetBias: bias)
38
124
  }
39
125
 
40
- // 撮影(キャプチャ取得).
41
126
  output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
42
127
  if error == nil {
43
128
 
44
- // imageFromImageBufferで取得したUIImageをJPEGに変換(これをDirectoryに保存).
129
+
45
130
  let image = self.imageFromImageBuffer(imageBuffer!)
46
131
  let JPEGdata = UIImageJPEGRepresentation(image!, 1)
47
132
 
48
- // ドキュメントと保存先のパス.
49
133
  let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
50
134
  print("書き込むファイルのパス: \(fileURL)")
51
135
 
52
- // 保存処理.
53
136
  do {
54
137
  try JPEGdata?.write(to: fileURL, options: .atomic)
55
138
  } catch {
@@ -62,37 +145,30 @@
62
145
  }
63
146
  }
64
147
  }
148
+
149
+ // imageBufferからUIImageに変換.
150
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
65
151
 
66
- // imageBufferからUIImageに変換.
67
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? { // 調べる ImageBufferの型 1つにたくさんだったらそのまま送れる 1つに1枚なら指定しなきゃ
68
-
69
- // imageBufferを確認.
70
152
  if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
71
153
 
72
- // 取得データのピクセル情報をロック.
73
154
  CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
74
155
 
75
- // ピクセルデータのパラメータ登場.
76
156
  let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
77
157
  let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
78
158
  let width = CVPixelBufferGetWidth(imageBuffer)
79
159
  let height = CVPixelBufferGetHeight(imageBuffer)
80
160
  let colorSpace = CGColorSpaceCreateDeviceRGB()
81
161
 
82
- // パラメータを載せる.
83
162
  guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
84
163
 
85
- // エラーの場合エラーを表示させる.
86
164
  print("Couldn't create context for image.")
87
165
  return nil
88
166
  }
89
167
 
90
168
  let quartzImage = context.makeImage()
91
169
 
92
- // 取得データのピクセル情報をロック解除.
93
170
  CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
94
171
 
95
- // 取得した情報からUIImageとJPEGデータを作成.
96
172
  if let quartzImage = quartzImage {
97
173
 
98
174
  // UIImage.
@@ -103,39 +179,42 @@
103
179
  }
104
180
  return nil
105
181
  }
106
-
107
- /*
182
+
108
- アップロード開始ボタンのイベント.
109
- */
110
- func tappedSentToServerButton(_ fileURL: NSData) {
183
+ func tappedSentToServerButton(_ sender: UIButton) {
111
184
 
112
- // 通信のリクエスト生成.
113
- let myCofig: URLSessionConfiguration = URLSessionConfiguration.default
185
+ let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
114
186
 
187
+ var fileNames: [String] {
188
+ do {
115
- let url:NSURL = NSURL(string: "http://*****.php")!
189
+ return try FileManager.default.contentsOfDirectory(atPath: documentPath)
190
+ } catch {
191
+ return []
192
+ }
193
+ }
116
194
 
195
+ return fileNames.flatMap { fileName in
196
+ do {
197
+ var datas: [NSData] = try url(contentsOfFile: documentPath + "/" + fileName, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)).lines
198
+ datas = datas.deleteSpaceOnly(datas: datas)
199
+ return datas
200
+
201
+ let myConfig: URLSessionConfiguration = URLSessionConfiguration.default
202
+ let url: NSURL = NSURL(string: "http://***.php")
117
- var request: URLRequest = URLRequest(url: url as URL)
203
+ var request: URLRequest = URLRequest(url: url as URL)
118
- request.httpMethod = "POST"
204
+ request.httpMethod = "POST"
119
-
120
- let session:URLSession = URLSession(configuration: myCofig, delegate: self, delegateQueue: OperationQueue.main)
205
+ let session: URLSession = URLSession(configuration: myConfig, delegate: self, delegateQueue: OperationQueue.main)
121
-
122
- let task:URLSessionUploadTask = session.uploadTask(with: request, from: fileURL as Data)
206
+ let task: URLSessionUploadTask = session.uploadTask(with: request, from: datas as Data)
123
-
124
- // タスクの実行.
207
+
125
- task.resume()
208
+ task.resume()
126
-
209
+ } catch {
127
-
210
+ return nil
211
+ }
128
212
  }
129
-
130
- ```
213
+ }
214
+
131
- ```php
215
+ override func didReceiveMemoryWarning() {
132
- <?php
216
+ super.didReceiveMemoryWarning()
133
-
134
- // リクエストBodyからファイルのデータを保存
217
+ // Dispose of any resources that can be recreated.
135
- $image = file_get_contents("php://input");
136
-
137
- // 受け取った値の表示
138
- echo $_POST;
139
-
140
- ?>
218
+ }
219
+ }
141
220
  ```

4

upload

2017/07/06 09:13

投稿

fujico23
fujico23

スコア13

title CHANGED
File without changes
body CHANGED
File without changes

3

質問内容の変更

2017/07/04 09:35

投稿

fujico23
fujico23

スコア13

title CHANGED
@@ -1,1 +1,1 @@
1
- カメラで取得した画像POST通するとエラーが出てまう
1
+ Swift:Directory内に保存した複数JPEGデータ一括送信したい
body CHANGED
@@ -1,11 +1,17 @@
1
1
  ###前提・実現したいこと
2
- iPhone cameraで撮影した写真をPOST通信するアプリを作成しています。
2
+ iPhone cameraで撮影したSampleBufferJPEGに変え、Directoryに保存し、一括でPOST通信するアプリを作成しています。
3
+ 写真はTimer関数を用いて複数枚とっています。
3
- 実機シミュレーションで、ビルドは通りますが、撮影した瞬間にエラーが出てしまいます。
4
+ 実機シミュレーションで、ビルドは通りますが、POST送信するところで以下のエラーが出てしまいます。
5
+ サーバに送付するところのコードがどこか間違っているのだと思いますが、ご教示頂ければ幸いです。
4
6
 
7
+ よろしくお願いいたします。
8
+
5
9
  ###発生している問題・エラーメッセージ
6
10
 
7
11
  ```
8
- error=Optional(Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSErrorFailingURLStringKey=http://****, _kCFStreamErrorCodeKey=61, NSErrorFailingURLKey=http://******.php, NSLocalizedDescription=Could not connect to the server., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x16563140 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61}}})
12
+ Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton copyWithZone:]: unrecognized selector sent to instance 0x14da0890'
13
+
14
+ libc++abi.dylib: terminating with uncaught exception of type NSException
9
15
  ```
10
16
 
11
17
  ###該当のソースコード
@@ -13,7 +19,8 @@
13
19
  /*
14
20
  撮影
15
21
  */
22
+ // 撮影する関数.
16
- func captureStillImage() {
23
+ func captureStillImage() {
17
24
 
18
25
  // 出力先が正しいことを確認.
19
26
  if let output = myImageOutput {
@@ -33,19 +40,31 @@
33
40
  // 撮影(キャプチャ取得).
34
41
  output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
35
42
  if error == nil {
36
- self.imageFromImageBuffer(imageBuffer!)
43
+
44
+ // imageFromImageBufferで取得したUIImageをJPEGに変換(これをDirectoryに保存).
45
+ let image = self.imageFromImageBuffer(imageBuffer!)
46
+ let JPEGdata = UIImageJPEGRepresentation(image!, 1)
47
+
48
+ // ドキュメントと保存先のパス.
49
+ let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
50
+ print("書き込むファイルのパス: \(fileURL)")
51
+
52
+ // 保存処理.
53
+ do {
54
+ try JPEGdata?.write(to: fileURL, options: .atomic)
55
+ } catch {
56
+ print("保存に失敗:\(error)")
57
+ }
58
+ } else {
59
+ print("JPEG取得に失敗:\(error)")
37
60
  }
38
-
39
61
  })
40
62
  }
41
63
  }
42
64
  }
43
65
 
44
- /*
45
- アップロード開始ボタンのイベント.
46
- */
47
- // imageBufferからjpegに変換.
66
+ // imageBufferからUIImageに変換.
48
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
67
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? { // 調べる ImageBufferの型 1つにたくさんだったらそのまま送れる 1つに1枚なら指定しなきゃ
49
68
 
50
69
  // imageBufferを確認.
51
70
  if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
@@ -67,6 +86,7 @@
67
86
  print("Couldn't create context for image.")
68
87
  return nil
69
88
  }
89
+
70
90
  let quartzImage = context.makeImage()
71
91
 
72
92
  // 取得データのピクセル情報をロック解除.
@@ -78,81 +98,35 @@
78
98
  // UIImage.
79
99
  let image = UIImage(cgImage: quartzImage)
80
100
 
81
- // JPEGデータ.
82
- let imageJPEGdata = UIImageJPEGRepresentation(image, 1)
83
-
84
- // 通信のリクエスト生成.
85
- let uploadScriptUrl = NSURL(string:"http://localhost/*****/phpinfo.php")
86
- let request = NSMutableURLRequest(url: uploadScriptUrl! as URL)
87
- request.httpMethod = "POST"
88
- request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
89
- let configuration: URLSessionConfiguration = URLSessionConfiguration.default
90
- let session:URLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
91
-
92
-
93
- // アップロード用のタスクを生成.
94
- let task: URLSessionUploadTask = session.uploadTask(with: request as URLRequest, from: imageJPEGdata!) {
95
-
96
- data, response, error in
97
-
98
- if error != nil {
99
-
100
- print("error=\(error)")
101
-
102
- return
103
- }
104
- }
105
-
106
- // タスクの実行.
107
- task.resume()
108
-
109
101
  return image
110
102
  }
111
103
  }
112
104
  return nil
113
105
  }
114
-
106
+
115
- /*
107
+ /*
116
- 通信終了時に呼び出されるデリゲート.
108
+ アップロド開始ボタンのイベント.
117
- */
109
+ */
118
- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
119
- print("didCompleteWithError")
110
+ func tappedSentToServerButton(_ fileURL: NSData) {
120
111
 
121
- // UIAlertControllerを作する.
112
+ // 通信のリクエスト生成.
122
- let myAlert: UIAlertController = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert)
113
+ let myCofig: URLSessionConfiguration = URLSessionConfiguration.default
123
114
 
124
- // OKのアクションを作成する.
125
- let myOkAction = UIAlertAction(title: "OK", style: .default) { action in
115
+ let url:NSURL = NSURL(string: "http://*****.php")!
126
- print("OK")
127
- }
128
116
 
129
- // OKのActionを追加する.
117
+ var request: URLRequest = URLRequest(url: url as URL)
130
- myAlert.addAction(myOkAction)
118
+ request.httpMethod = "POST"
131
119
 
132
- // UIAlertを発動する.
133
- present(myAlert, animated: true, completion: nil)
134
- }
135
-
136
- func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
120
+ let session:URLSession = URLSession(configuration: myCofig, delegate: self, delegateQueue: OperationQueue.main)
137
121
 
138
- print("didSendBodyData")
139
- let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
122
+ let task:URLSessionUploadTask = session.uploadTask(with: request, from: fileURL as Data)
140
- myProgress.progress = uploadProgress
141
- let progressPercent = Int(uploadProgress*100)
142
- myProgressLabel.text = "\(progressPercent)%"
143
- print(uploadProgress)
144
- }
145
-
146
- private func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
147
- print("didReceiveResponse")
148
- print(response);
149
123
 
150
- }
151
-
152
- func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
153
- print("didReceiveData")
124
+ // タスクの実行.
154
- }
125
+ task.resume()
155
126
 
127
+
128
+ }
129
+
156
130
  ```
157
131
  ```php
158
132
  <?php
@@ -164,7 +138,4 @@
164
138
  echo $_POST;
165
139
 
166
140
  ?>
167
- ```
141
+ ```
168
-
169
- ###試したこと
170
- Info.plistに「NSAppTransportSecurity」をDictionaryで作成し、「NSAllowsArbitraryLoads」をBoolean型としてYESにしましたが、変わらずでした。

2

質問内容の編集

2017/06/30 13:45

投稿

fujico23
fujico23

スコア13

title CHANGED
@@ -1,1 +1,1 @@
1
- Swift:CoreDataに保存した画像データPostgreSQLにアップロたい
1
+ カメラで取得した画像をPOST通信するとエラが出てまう
body CHANGED
@@ -1,159 +1,159 @@
1
1
  ###前提・実現したいこと
2
- iPhone cameraで撮影した写真をCoreDataに保存し、そのデータをPOST通信するアプリを作成しています。
2
+ iPhone cameraで撮影した写真をPOST通信するアプリを作成しています。
3
- 撮影する能とそれをCoreDataに保存する機能実装できました。
3
+ シミュレーションでビルド通りすが、撮影した瞬間にエラーが出てしまいます
4
4
 
5
- CoreDataに保存されたデータをPOST通信する際、そのデータはどのように定義たら良でしょうか。
5
+ ###発生る問題・エラーメッセージ
6
6
 
7
+ ```
8
+ error=Optional(Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSErrorFailingURLStringKey=http://****, _kCFStreamErrorCodeKey=61, NSErrorFailingURLKey=http://******.php, NSLocalizedDescription=Could not connect to the server., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x16563140 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61}}})
9
+ ```
7
10
 
8
- ご教示お願いいたします。
9
-
10
-
11
-
12
- ###実装した部分のソースコード
11
+ ###該当のソースコード
13
12
  ```Swift
14
13
  /*
15
14
  撮影
16
15
  */
17
16
  func captureStillImage() {
17
+
18
+ // 出力先が正しいことを確認.
18
19
  if let output = myImageOutput {
20
+
21
+ // キュー.
19
22
  DispatchQueue.global().async {
23
+
24
+ // 撮影の設定.
20
25
  let connection = output.connection(withMediaType: AVMediaTypeVideo)
26
+
27
+ // 撮影する露光時間を±2.0に設定.
21
28
  let settings = [-2.0, 0.0, 2.0].map {
22
29
  (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
23
30
  AVCaptureAutoExposureBracketedStillImageSettings.autoExposureSettings(withExposureTargetBias: bias)
24
31
  }
32
+
33
+ // 撮影(キャプチャ取得).
25
34
  output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
26
35
  if error == nil {
27
36
  self.imageFromImageBuffer(imageBuffer!)
28
37
  }
38
+
29
39
  })
30
40
  }
31
41
  }
32
42
  }
33
43
 
34
44
  /*
35
- imageBufferをJPEGに変換
45
+ アップロード開始ボタンのイベント.
36
46
  */
47
+ // imageBufferからjpegに変換.
37
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
48
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
49
+
50
+ // imageBufferを確認.
38
51
  if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
52
+
53
+ // 取得データのピクセル情報をロック.
39
54
  CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
55
+
56
+ // ピクセルデータのパラメータ登場.
40
57
  let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
41
58
  let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
42
59
  let width = CVPixelBufferGetWidth(imageBuffer)
43
60
  let height = CVPixelBufferGetHeight(imageBuffer)
44
61
  let colorSpace = CGColorSpaceCreateDeviceRGB()
62
+
45
-
63
+ // パラメータを載せる.
46
64
  guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
47
65
 
66
+ // エラーの場合エラーを表示させる.
48
67
  print("Couldn't create context for image.")
49
68
  return nil
50
69
  }
51
70
  let quartzImage = context.makeImage()
52
71
 
72
+ // 取得データのピクセル情報をロック解除.
53
73
  CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
54
74
 
55
75
  // 取得した情報からUIImageとJPEGデータを作成.
56
76
  if let quartzImage = quartzImage {
57
77
 
78
+ // UIImage.
58
79
  let image = UIImage(cgImage: quartzImage)
80
+
81
+ // JPEGデータ.
59
82
  let imageJPEGdata = UIImageJPEGRepresentation(image, 1)
60
-
61
83
 
62
- /*
84
+ // 通信のリクエスト生成.
85
+ let uploadScriptUrl = NSURL(string:"http://localhost/*****/phpinfo.php")
86
+ let request = NSMutableURLRequest(url: uploadScriptUrl! as URL)
63
- JPEGをCoreDataに保存
87
+ request.httpMethod = "POST"
64
- */
88
+ request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
65
- let appDel: AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
89
+ let configuration: URLSessionConfiguration = URLSessionConfiguration.default
90
+ let session:URLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
66
91
 
67
- let context: NSManagedObjectContext = appDel.managedObjectContext
68
-
69
- let myEntity: NSEntityDescription! = NSEntityDescription.entity(forEntityName: "MyCoreDataStore", in: context)
70
92
 
93
+ // アップロード用のタスクを生成.
71
- let newData = MyCoreDataStore(entity: myEntity, insertInto: context)
94
+ let task: URLSessionUploadTask = session.uploadTask(with: request as URLRequest, from: imageJPEGdata!) {
95
+
96
+ data, response, error in
97
+
98
+ if error != nil {
99
+
100
+ print("error=\(error)")
101
+
102
+ return
103
+ }
104
+ }
72
105
 
106
+ // タスクの実行.
107
+ task.resume()
73
108
 
74
- newData.photo = imageJPEGdata as NSData?
75
- newData.time = NSDate()
76
-
77
- (UIApplication.shared.delegate as! AppDelegate).saveContext()
78
-
79
-
80
-
81
109
  return image
82
110
  }
83
-
84
111
  }
85
112
  return nil
86
113
  }
87
-
88
- ```
114
+
89
-
90
- ###試したこと
115
+ /*
116
+ 通信終了時に呼び出されるデリゲート.
117
+ */
118
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
91
- 以下がCoreDataに保存されたデータをPOST通信する部分のコードです。
119
+ print("didCompleteWithError")
92
- ```swift
93
120
 
94
- /*
95
-
96
- ここでCoreData内のデータ定義するのではないかと考えています。
121
+ // UIAlertController作成する.
97
- /*
122
+ let myAlert: UIAlertController = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert)
98
123
 
99
-
124
+ // OKのアクションを作成する.
100
- let url = NSURL(string: "http://****.php")
125
+ let myOkAction = UIAlertAction(title: "OK", style: .default) { action in
101
- let urlRequest: NSMutableURLRequest = NSMutableURLRequest()
102
-
103
- if let u = url {
104
-
105
- urlRequest.url = u as URL
106
- urlRequest.httpMethod = "POST"
126
+ print("OK")
107
-
108
-
109
127
  }
110
128
 
129
+ // OKのActionを追加する.
130
+ myAlert.addAction(myOkAction)
111
131
 
112
- let uniqueId = ProcessInfo.processInfo.globallyUniqueString
132
+ // UIAlertを発動する.
113
- let body: NSMutableData = NSMutableData()
133
+ present(myAlert, animated: true, completion: nil)
114
- var postData: String = String()
134
+ }
135
+
115
- let boundary: String = "---------------------------\(uniqueId)"
136
+ func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
116
137
 
138
+ print("didSendBodyData")
139
+ let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
140
+ myProgress.progress = uploadProgress
141
+ let progressPercent = Int(uploadProgress*100)
142
+ myProgressLabel.text = "\(progressPercent)%"
143
+ print(uploadProgress)
144
+ }
145
+
146
+ private func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
147
+ print("didReceiveResponse")
148
+ print(response);
117
149
 
118
-
119
- urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
120
-
121
- postData += "--\(boundary)\r\n"
122
-
123
-
124
- postData += "Content-Disposition: form-data; name=\"image\"; filename=\"images.jpg\"\r\n"
125
- postData += "Content-Type: image/jpeg\r\n\r\n"
126
- body.append(postData.data(using: String.Encoding.utf8)!)
127
- body.append(file as Data)
128
-
129
- postData = String()
130
- postData += "\r\n"
131
- postData += "\r\n--\(boundary)--\r\n"
132
-
133
-
134
- body.append(postData.data(using: String.Encoding.utf8)!)
135
-
136
- urlRequest.httpBody = NSData(data: body as Data) as Data
137
- print(urlRequest)
138
-
139
- // send request and recieve response
140
- let config = URLSessionConfiguration.default
141
- let session = URLSession(configuration: config)
142
-
143
- let task: URLSessionDataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { data, request, error in
144
-
145
- // reterned data from serverSide
146
- let result = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
147
- print("result=\(result)")
148
-
149
- })
150
- task.resume()
151
-
152
-
153
150
  }
151
+
152
+ func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
153
+ print("didReceiveData")
154
+ }
154
155
 
155
156
  ```
156
-
157
157
  ```php
158
158
  <?php
159
159
 
@@ -164,4 +164,7 @@
164
164
  echo $_POST;
165
165
 
166
166
  ?>
167
- ```
167
+ ```
168
+
169
+ ###試したこと
170
+ Info.plistに「NSAppTransportSecurity」をDictionaryで作成し、「NSAllowsArbitraryLoads」をBoolean型としてYESにしましたが、変わらずでした。

1

具体化

2017/06/28 06:08

投稿

fujico23
fujico23

スコア13

title CHANGED
File without changes
body CHANGED
@@ -1,8 +1,8 @@
1
1
  ###前提・実現したいこと
2
- アイフォンカメラで撮影した写真をCoreDataに保存し、そのデータをPostgreSQLにアップロードするアプリを作成しています。
2
+ iPhone cameraで撮影した写真をCoreDataに保存し、そのデータをPOST通信するアプリを作成しています。
3
3
  撮影する機能と、それをCoreDataに保存する機能は実装できました。
4
4
 
5
- 具体的にCoreDataデータをPostgreSQLにアップロードするためにはどうすればよいでしょうか。
5
+ CoreDataに保存されたデータをPOST通信する際、そのデータはどうに定義したら良いでしょうか。
6
6
 
7
7
 
8
8
  ご教示お願いいたします。
@@ -88,37 +88,24 @@
88
88
  ```
89
89
 
90
90
  ###試したこと
91
- まず、ApacheおよびPHPファイルをMacインストールしました。
91
+ 以下がCoreData保存されデータをPOST通信する部分のコードです
92
- その後今回開発したいアプリとは別のアプリを練習として作成し、画像をApacheに通信するコードを書いてみました。
93
92
  ```swift
93
+
94
- import UIKit
94
+ /*
95
95
 
96
- class ViewController: UIViewController, URLSessionTaskDelegate {
96
+ ここでCoreData内のデータを定義するのではないかと考えています。
97
-
98
- var json: NSData!
97
+ /*
99
-
98
+
100
99
 
101
- override func viewDidLoad() {
102
- super.viewDidLoad()
103
-
104
- upload()
105
-
106
- }
107
-
108
- func upload() {
109
-
110
- let sampleImage = UIImage(named: "myimage.jpg")
111
- let file: NSData = NSData(data: UIImageJPEGRepresentation(sampleImage!, 1.0)!)
112
-
113
- let url = NSURL(string: "http://********.php")
100
+ let url = NSURL(string: "http://****.php")
114
101
  let urlRequest: NSMutableURLRequest = NSMutableURLRequest()
115
102
 
116
103
  if let u = url {
117
104
 
118
105
  urlRequest.url = u as URL
119
106
  urlRequest.httpMethod = "POST"
120
- // urlRequest.timeoutInterval = 30.0
121
107
 
108
+
122
109
  }
123
110
 
124
111
 
@@ -149,46 +136,22 @@
149
136
  urlRequest.httpBody = NSData(data: body as Data) as Data
150
137
  print(urlRequest)
151
138
 
152
-
139
+ // send request and recieve response
153
140
  let config = URLSessionConfiguration.default
154
141
  let session = URLSession(configuration: config)
155
142
 
156
143
  let task: URLSessionDataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { data, request, error in
157
144
 
158
-
145
+ // reterned data from serverSide
159
146
  let result = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
160
147
  print("result=\(result)")
161
148
 
162
149
  })
163
150
  task.resume()
164
151
 
152
+
165
153
  }
166
-
167
-
168
- //通信終了時に呼び出されるデリゲート
169
- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
170
- // print("didCompleteWithError")
171
- print("error: \(error)")
172
-
173
- }
174
-
175
- func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
176
- print("willPerformHTTPRedirection")
177
- }
178
-
179
- func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
180
- print("didSendBodyData")
181
- }
182
-
183
154
 
184
- override func didReceiveMemoryWarning() {
185
- super.didReceiveMemoryWarning()
186
- // Dispose of any resources that can be recreated.
187
- }
188
-
189
-
190
- }
191
-
192
155
  ```
193
156
 
194
157
  ```php
@@ -201,7 +164,4 @@
201
164
  echo $_POST;
202
165
 
203
166
  ?>
204
- ```
167
+ ```
205
-
206
- ###補足情報(言語/FW/ツール等のバージョンなど)
207
- 記載したコードで間違っている箇所があればご指摘頂けると幸いです。