質問編集履歴

7

コード編集

2017/07/07 03:19

投稿

fujico23
fujico23

スコア13

test CHANGED
File without changes
test CHANGED
@@ -25,12 +25,6 @@
25
25
  ###該当のソースコード
26
26
 
27
27
  ```Swift
28
-
29
-
30
-
31
-
32
-
33
- func tappedSentToServerButton(_ sender: UIButton) {
34
28
 
35
29
 
36
30
 
@@ -64,33 +58,7 @@
64
58
 
65
59
  return datas
66
60
 
67
-
68
-
69
- let myConfig: URLSessionConfiguration = URLSessionConfiguration.default
70
-
71
- let url: NSURL = NSURL(string: "http://***.php")
72
-
73
- var request: URLRequest = URLRequest(url: url as URL)
74
-
75
- request.httpMethod = "POST"
76
-
77
- let session: URLSession = URLSession(configuration: myConfig, delegate: self, delegateQueue: OperationQueue.main)
78
-
79
- let task: URLSessionUploadTask = session.uploadTask(with: request, from: datas as Data)
80
-
81
-
82
-
83
- task.resume()
84
-
85
- } catch {
86
-
87
- return nil
88
-
89
- }
90
-
91
61
  }
92
-
93
- }
94
62
 
95
63
 
96
64
 

6

コードの編集

2017/07/07 03:18

投稿

fujico23
fujico23

スコア13

test CHANGED
File without changes
test CHANGED
@@ -26,339 +26,7 @@
26
26
 
27
27
  ```Swift
28
28
 
29
- import UIKit
30
29
 
31
- import AVFoundation
32
-
33
-
34
-
35
- class ViewController: UIViewController, UIGestureRecognizerDelegate, URLSessionTaskDelegate {
36
-
37
- var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
38
-
39
- var mySession : AVCaptureSession!
40
-
41
- var myDevice : AVCaptureDevice
42
-
43
- var myImageOutput: AVCaptureStillImageOutput!
44
-
45
- var myTimer = Timer()
46
-
47
- var second: Int = 30
48
-
49
- let SentToServerButton = UIButton()
50
-
51
- let playButton = UIButton()
52
-
53
-
54
-
55
- override func viewDidLoad() {
56
-
57
- super.viewDidLoad()
58
-
59
- let fileManager = FileManager.default
60
-
61
- do {
62
-
63
- let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
64
-
65
- if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
66
-
67
- while let fileURL = enumerator.nextObject() as? URL {
68
-
69
- try fileManager.removeItem(at: fileURL)
70
-
71
- }
72
-
73
- }
74
-
75
- } catch {
76
-
77
- print("削除に失敗 \n \(error)")
78
-
79
- }
80
-
81
- mySession = AVCaptureSession()
82
-
83
- mySession.sessionPreset = AVCaptureSessionPresetHigh
84
-
85
- let devices = AVCaptureDevice.devices()
86
-
87
- for device in devices! {
88
-
89
- if((device as AnyObject).position == AVCaptureDevicePosition.back){
90
-
91
- myDevice = device as! AVCaptureDevice
92
-
93
- }
94
-
95
- }
96
-
97
- let videoInput = try! AVCaptureDeviceInput.init(device: myDevice)
98
-
99
- mySession.addInput(videoInput)
100
-
101
- myImageOutput = AVCaptureStillImageOutput()
102
-
103
- myImageOutput.outputSettings = [ kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA ]
104
-
105
- mySession.addOutput(myImageOutput)
106
-
107
- for connection in myImageOutput.connections {
108
-
109
- if let conn = connection as? AVCaptureConnection {
110
-
111
- if conn.isVideoOrientationSupported {
112
-
113
- conn.videoOrientation = AVCaptureVideoOrientation.portrait
114
-
115
- }
116
-
117
- }
118
-
119
- }
120
-
121
- let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
122
-
123
- myVideoLayer?.frame = self.view.bounds
124
-
125
- myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
126
-
127
- self.view.layer.addSublayer(myVideoLayer!)
128
-
129
- mySession.startRunning()
130
-
131
- let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedScreen))
132
-
133
- tapGesture.delegate = self
134
-
135
- self.view.addGestureRecognizer(tapGesture)
136
-
137
- playButton.setTitle("撮影開始", for: .normal)
138
-
139
- playButton.frame = CGRect(x: 120, y: 450, width: 80, height: 80)
140
-
141
- playButton.setTitleColor(UIColor.black, for: UIControlState())
142
-
143
- playButton.layer.position = CGPoint(x: view.frame.width / 2, y: self.view.bounds.size.height - 80)
144
-
145
- playButton.backgroundColor = UIColor.red
146
-
147
- playButton.addTarget(self, action: #selector(ViewController.tappedPlayButton), for: .touchUpInside)
148
-
149
- self.view.addSubview(playButton)
150
-
151
-
152
-
153
- SentToServerButton.setTitle("サーバに送付", for: .normal)
154
-
155
- SentToServerButton.contentMode = .scaleAspectFit
156
-
157
- SentToServerButton.frame = CGRect(x: 300, y: 200, width: 120, height: 50)
158
-
159
- SentToServerButton.backgroundColor = UIColor.black
160
-
161
- SentToServerButton.setTitleColor(UIColor.white, for: UIControlState())
162
-
163
- SentToServerButton.layer.position = CGPoint(x: view.frame.width / 2 + 80, y: self.view.bounds.size.height - 300)
164
-
165
- SentToServerButton.addTarget(self, action: #selector(ViewController.tappedSentToServerButton), for: .touchUpInside)
166
-
167
- view.addSubview(SentToServerButton)
168
-
169
- }
170
-
171
-
172
-
173
-
174
-
175
- func tappedPlayButton(sender: UIButton) {
176
-
177
-
178
-
179
- print("start!")
180
-
181
-
182
-
183
- playButton.isHidden = true
184
-
185
-
186
-
187
- second = 30
188
-
189
-
190
-
191
- myTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.TemporalEvent), userInfo: nil, repeats: true)
192
-
193
-
194
-
195
-
196
-
197
- }
198
-
199
-
200
-
201
-
202
-
203
- func TemporalEvent(){
204
-
205
-
206
-
207
-
208
-
209
- second -= 3
210
-
211
-
212
-
213
- captureStillImage()
214
-
215
- if second == 0 {
216
-
217
- myTimer.invalidate()
218
-
219
- }
220
-
221
- }
222
-
223
-
224
-
225
- func captureStillImage() {
226
-
227
-
228
-
229
- if let output = myImageOutput {
230
-
231
-
232
-
233
- DispatchQueue.global().async {
234
-
235
-
236
-
237
- let connection = output.connection(withMediaType: AVMediaTypeVideo)
238
-
239
-
240
-
241
- let settings = [-1.0, 0.0, 2.5].map {
242
-
243
- (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
244
-
245
- AVCaptureAutoExposureBracketedStillImageSettings.autoExposureSettings(withExposureTargetBias: bias)
246
-
247
- }
248
-
249
-
250
-
251
- output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
252
-
253
- if error == nil {
254
-
255
-
256
-
257
-
258
-
259
- let image = self.imageFromImageBuffer(imageBuffer!)
260
-
261
- let JPEGdata = UIImageJPEGRepresentation(image!, 1)
262
-
263
-
264
-
265
- let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
266
-
267
- print("書き込むファイルのパス: \(fileURL)")
268
-
269
-
270
-
271
- do {
272
-
273
- try JPEGdata?.write(to: fileURL, options: .atomic)
274
-
275
- } catch {
276
-
277
- print("保存に失敗:\(error)")
278
-
279
- }
280
-
281
- } else {
282
-
283
- print("JPEG取得に失敗:\(error)")
284
-
285
- }
286
-
287
- })
288
-
289
- }
290
-
291
- }
292
-
293
- }
294
-
295
-
296
-
297
- // imageBufferからUIImageに変換.
298
-
299
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
300
-
301
-
302
-
303
- if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
304
-
305
-
306
-
307
- CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
308
-
309
-
310
-
311
- let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
312
-
313
- let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
314
-
315
- let width = CVPixelBufferGetWidth(imageBuffer)
316
-
317
- let height = CVPixelBufferGetHeight(imageBuffer)
318
-
319
- let colorSpace = CGColorSpaceCreateDeviceRGB()
320
-
321
-
322
-
323
- guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
324
-
325
-
326
-
327
- print("Couldn't create context for image.")
328
-
329
- return nil
330
-
331
- }
332
-
333
-
334
-
335
- let quartzImage = context.makeImage()
336
-
337
-
338
-
339
- CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
340
-
341
-
342
-
343
- if let quartzImage = quartzImage {
344
-
345
-
346
-
347
- // UIImage.
348
-
349
- let image = UIImage(cgImage: quartzImage)
350
-
351
-
352
-
353
- return image
354
-
355
- }
356
-
357
- }
358
-
359
- return nil
360
-
361
- }
362
30
 
363
31
 
364
32
 
@@ -426,14 +94,6 @@
426
94
 
427
95
 
428
96
 
429
- override func didReceiveMemoryWarning() {
97
+
430
-
431
- super.didReceiveMemoryWarning()
432
-
433
- // Dispose of any resources that can be recreated.
434
-
435
- }
436
-
437
- }
438
98
 
439
99
  ```

5

コードの編集

2017/07/07 00:56

投稿

fujico23
fujico23

スコア13

test CHANGED
File without changes
test CHANGED
@@ -4,13 +4,9 @@
4
4
 
5
5
  写真はTimer関数を用いて複数枚とっています。
6
6
 
7
- 実機シミュレーションで、ビルドは通りますが、POST送信するところで以下のエラーが出てしまいます。
7
+ 実機シミュレーションで、以下のエラーが出てしまいます。
8
-
9
- サーバに送付するところのコードがどこか間違っているのだと思いますが、ご教示頂ければ幸いです。
8
+
10
-
11
-
12
-
13
- よろしくお願いたします。
9
+ ご教示頂ければ幸す。
14
10
 
15
11
 
16
12
 
@@ -20,11 +16,7 @@
20
16
 
21
17
  ```
22
18
 
23
- Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton copyWithZone:]: unrecognized selector sent to instance 0x14da0890'
19
+ 'flatMap' produces '[SegmentOfResult.Iterator.Element]', not the expected contextual result type '()'
24
-
25
-
26
-
27
- libc++abi.dylib: terminating with uncaught exception of type NSException
28
20
 
29
21
  ```
30
22
 
@@ -34,39 +26,219 @@
34
26
 
35
27
  ```Swift
36
28
 
37
- /*
29
+ import UIKit
38
-
39
- 撮影
30
+
40
-
41
- */
42
-
43
- // 撮影する関数.
31
+ import AVFoundation
32
+
33
+
34
+
35
+ class ViewController: UIViewController, UIGestureRecognizerDelegate, URLSessionTaskDelegate {
36
+
37
+ var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
38
+
39
+ var mySession : AVCaptureSession!
40
+
41
+ var myDevice : AVCaptureDevice
42
+
43
+ var myImageOutput: AVCaptureStillImageOutput!
44
+
45
+ var myTimer = Timer()
46
+
47
+ var second: Int = 30
48
+
49
+ let SentToServerButton = UIButton()
50
+
51
+ let playButton = UIButton()
52
+
53
+
54
+
55
+ override func viewDidLoad() {
56
+
57
+ super.viewDidLoad()
58
+
59
+ let fileManager = FileManager.default
60
+
61
+ do {
62
+
63
+ let url = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
64
+
65
+ if let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) {
66
+
67
+ while let fileURL = enumerator.nextObject() as? URL {
68
+
69
+ try fileManager.removeItem(at: fileURL)
70
+
71
+ }
72
+
73
+ }
74
+
75
+ } catch {
76
+
77
+ print("削除に失敗 \n \(error)")
78
+
79
+ }
80
+
81
+ mySession = AVCaptureSession()
82
+
83
+ mySession.sessionPreset = AVCaptureSessionPresetHigh
84
+
85
+ let devices = AVCaptureDevice.devices()
86
+
87
+ for device in devices! {
88
+
89
+ if((device as AnyObject).position == AVCaptureDevicePosition.back){
90
+
91
+ myDevice = device as! AVCaptureDevice
92
+
93
+ }
94
+
95
+ }
96
+
97
+ let videoInput = try! AVCaptureDeviceInput.init(device: myDevice)
98
+
99
+ mySession.addInput(videoInput)
100
+
101
+ myImageOutput = AVCaptureStillImageOutput()
102
+
103
+ myImageOutput.outputSettings = [ kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA ]
104
+
105
+ mySession.addOutput(myImageOutput)
106
+
107
+ for connection in myImageOutput.connections {
108
+
109
+ if let conn = connection as? AVCaptureConnection {
110
+
111
+ if conn.isVideoOrientationSupported {
112
+
113
+ conn.videoOrientation = AVCaptureVideoOrientation.portrait
114
+
115
+ }
116
+
117
+ }
118
+
119
+ }
120
+
121
+ let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
122
+
123
+ myVideoLayer?.frame = self.view.bounds
124
+
125
+ myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
126
+
127
+ self.view.layer.addSublayer(myVideoLayer!)
128
+
129
+ mySession.startRunning()
130
+
131
+ let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedScreen))
132
+
133
+ tapGesture.delegate = self
134
+
135
+ self.view.addGestureRecognizer(tapGesture)
136
+
137
+ playButton.setTitle("撮影開始", for: .normal)
138
+
139
+ playButton.frame = CGRect(x: 120, y: 450, width: 80, height: 80)
140
+
141
+ playButton.setTitleColor(UIColor.black, for: UIControlState())
142
+
143
+ playButton.layer.position = CGPoint(x: view.frame.width / 2, y: self.view.bounds.size.height - 80)
144
+
145
+ playButton.backgroundColor = UIColor.red
146
+
147
+ playButton.addTarget(self, action: #selector(ViewController.tappedPlayButton), for: .touchUpInside)
148
+
149
+ self.view.addSubview(playButton)
150
+
151
+
152
+
153
+ SentToServerButton.setTitle("サーバに送付", for: .normal)
154
+
155
+ SentToServerButton.contentMode = .scaleAspectFit
156
+
157
+ SentToServerButton.frame = CGRect(x: 300, y: 200, width: 120, height: 50)
158
+
159
+ SentToServerButton.backgroundColor = UIColor.black
160
+
161
+ SentToServerButton.setTitleColor(UIColor.white, for: UIControlState())
162
+
163
+ SentToServerButton.layer.position = CGPoint(x: view.frame.width / 2 + 80, y: self.view.bounds.size.height - 300)
164
+
165
+ SentToServerButton.addTarget(self, action: #selector(ViewController.tappedSentToServerButton), for: .touchUpInside)
166
+
167
+ view.addSubview(SentToServerButton)
168
+
169
+ }
170
+
171
+
172
+
173
+
174
+
175
+ func tappedPlayButton(sender: UIButton) {
176
+
177
+
178
+
179
+ print("start!")
180
+
181
+
182
+
183
+ playButton.isHidden = true
184
+
185
+
186
+
187
+ second = 30
188
+
189
+
190
+
191
+ myTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.TemporalEvent), userInfo: nil, repeats: true)
192
+
193
+
194
+
195
+
196
+
197
+ }
198
+
199
+
200
+
201
+
202
+
203
+ func TemporalEvent(){
204
+
205
+
206
+
207
+
208
+
209
+ second -= 3
210
+
211
+
212
+
213
+ captureStillImage()
214
+
215
+ if second == 0 {
216
+
217
+ myTimer.invalidate()
218
+
219
+ }
220
+
221
+ }
222
+
223
+
44
224
 
45
225
  func captureStillImage() {
46
226
 
47
-
48
-
49
- // 出力先が正しいことを確認.
227
+
50
228
 
51
229
  if let output = myImageOutput {
52
230
 
53
-
54
-
55
- // キュー.
231
+
56
232
 
57
233
  DispatchQueue.global().async {
58
234
 
59
-
60
-
61
- // 撮影の設定.
235
+
62
236
 
63
237
  let connection = output.connection(withMediaType: AVMediaTypeVideo)
64
238
 
65
239
 
66
240
 
67
- // 撮影する露光時間を±2.0に設定.
68
-
69
- let settings = [-2.0, 0.0, 2.0].map {
241
+ let settings = [-1.0, 0.0, 2.5].map {
70
242
 
71
243
  (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
72
244
 
@@ -76,15 +248,13 @@
76
248
 
77
249
 
78
250
 
79
- // 撮影(キャプチャ取得).
80
-
81
251
  output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
82
252
 
83
253
  if error == nil {
84
254
 
85
255
 
86
256
 
87
- // imageFromImageBufferで取得したUIImageをJPEGに変換(これをDirectoryに保存).
257
+
88
258
 
89
259
  let image = self.imageFromImageBuffer(imageBuffer!)
90
260
 
@@ -92,16 +262,12 @@
92
262
 
93
263
 
94
264
 
95
- // ドキュメントと保存先のパス.
96
-
97
265
  let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
98
266
 
99
267
  print("書き込むファイルのパス: \(fileURL)")
100
268
 
101
269
 
102
270
 
103
- // 保存処理.
104
-
105
271
  do {
106
272
 
107
273
  try JPEGdata?.write(to: fileURL, options: .atomic)
@@ -126,28 +292,22 @@
126
292
 
127
293
  }
128
294
 
129
-
130
-
295
+
296
+
131
- // imageBufferからUIImageに変換.
297
+ // imageBufferからUIImageに変換.
132
-
298
+
133
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? { // 調べる ImageBufferの型 1つにたくさんだったらそのまま送れる 1つに1枚なら指定しなきゃ
299
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
134
-
135
-
136
-
137
- // imageBufferを確認.
300
+
301
+
138
302
 
139
303
  if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
140
304
 
141
305
 
142
306
 
143
- // 取得データのピクセル情報をロック.
144
-
145
307
  CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
146
308
 
147
309
 
148
310
 
149
- // ピクセルデータのパラメータ登場.
150
-
151
311
  let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
152
312
 
153
313
  let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
@@ -160,14 +320,10 @@
160
320
 
161
321
 
162
322
 
163
- // パラメータを載せる.
164
-
165
323
  guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
166
324
 
167
325
 
168
326
 
169
- // エラーの場合エラーを表示させる.
170
-
171
327
  print("Couldn't create context for image.")
172
328
 
173
329
  return nil
@@ -180,14 +336,10 @@
180
336
 
181
337
 
182
338
 
183
- // 取得データのピクセル情報をロック解除.
184
-
185
339
  CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
186
340
 
187
341
 
188
342
 
189
- // 取得した情報からUIImageとJPEGデータを作成.
190
-
191
343
  if let quartzImage = quartzImage {
192
344
 
193
345
 
@@ -208,74 +360,80 @@
208
360
 
209
361
  }
210
362
 
211
-
212
-
213
- /*
214
-
215
- アップロード開始ボタンのイベント.
216
-
217
- */
218
-
219
- func tappedSentToServerButton(_ fileURL: NSData) {
220
-
221
-
222
-
223
- // 通信のリクエスト生成.
224
-
225
- let myCofig: URLSessionConfiguration = URLSessionConfiguration.default
226
-
227
-
228
-
229
- let url:NSURL = NSURL(string: "http://*****.php")!
230
-
231
-
232
-
233
- var request: URLRequest = URLRequest(url: url as URL)
234
-
235
- request.httpMethod = "POST"
236
-
237
-
238
-
239
- let session:URLSession = URLSession(configuration: myCofig, delegate: self, delegateQueue: OperationQueue.main)
240
-
241
-
242
-
243
- let task:URLSessionUploadTask = session.uploadTask(with: request, from: fileURL as Data)
244
-
245
-
246
-
247
- // タスクの実行.
248
-
249
- task.resume()
250
-
251
-
252
-
253
-
254
-
255
- }
256
-
257
-
363
+
364
+
365
+ func tappedSentToServerButton(_ sender: UIButton) {
366
+
367
+
368
+
369
+ let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
370
+
371
+
372
+
373
+ var fileNames: [String] {
374
+
375
+ do {
376
+
377
+ return try FileManager.default.contentsOfDirectory(atPath: documentPath)
378
+
379
+ } catch {
380
+
381
+ return []
382
+
383
+ }
384
+
385
+ }
386
+
387
+
388
+
389
+ return fileNames.flatMap { fileName in
390
+
391
+ do {
392
+
393
+ var datas: [NSData] = try url(contentsOfFile: documentPath + "/" + fileName, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)).lines
394
+
395
+ datas = datas.deleteSpaceOnly(datas: datas)
396
+
397
+ return datas
398
+
399
+
400
+
401
+ let myConfig: URLSessionConfiguration = URLSessionConfiguration.default
402
+
403
+ let url: NSURL = NSURL(string: "http://***.php")
404
+
405
+ var request: URLRequest = URLRequest(url: url as URL)
406
+
407
+ request.httpMethod = "POST"
408
+
409
+ let session: URLSession = URLSession(configuration: myConfig, delegate: self, delegateQueue: OperationQueue.main)
410
+
411
+ let task: URLSessionUploadTask = session.uploadTask(with: request, from: datas as Data)
412
+
413
+
414
+
415
+ task.resume()
416
+
417
+ } catch {
418
+
419
+ return nil
420
+
421
+ }
422
+
423
+ }
424
+
425
+ }
426
+
427
+
428
+
429
+ override func didReceiveMemoryWarning() {
430
+
431
+ super.didReceiveMemoryWarning()
432
+
433
+ // Dispose of any resources that can be recreated.
434
+
435
+ }
436
+
437
+ }
258
438
 
259
439
  ```
260
-
261
- ```php
262
-
263
- <?php
264
-
265
-
266
-
267
- // リクエストBodyからファイルのデータを保存
268
-
269
- $image = file_get_contents("php://input");
270
-
271
-
272
-
273
- // 受け取った値の表示
274
-
275
- echo $_POST;
276
-
277
-
278
-
279
- ?>
280
-
281
- ```

4

upload

2017/07/06 09:13

投稿

fujico23
fujico23

スコア13

test CHANGED
File without changes
test CHANGED
File without changes

3

質問内容の変更

2017/07/04 09:35

投稿

fujico23
fujico23

スコア13

test CHANGED
@@ -1 +1 @@
1
- カメラで取得した画像POST通するとエラーが出てまう
1
+ Swift:Directory内に保存した複数JPEGデータ一括送信したい
test CHANGED
@@ -1,8 +1,16 @@
1
1
  ###前提・実現したいこと
2
2
 
3
- iPhone cameraで撮影した写真をPOST通信するアプリを作成しています。
3
+ iPhone cameraで撮影したSampleBufferJPEGに変え、Directoryに保存し、一括でPOST通信するアプリを作成しています。
4
+
4
-
5
+ 写真はTimer関数を用いて複数枚とっています。
6
+
5
- 実機シミュレーションで、ビルドは通りますが、撮影した瞬間にエラーが出てしまいます。
7
+ 実機シミュレーションで、ビルドは通りますが、POST送信するところで以下のエラーが出てしまいます。
8
+
9
+ サーバに送付するところのコードがどこか間違っているのだと思いますが、ご教示頂ければ幸いです。
10
+
11
+
12
+
13
+ よろしくお願いいたします。
6
14
 
7
15
 
8
16
 
@@ -12,7 +20,11 @@
12
20
 
13
21
  ```
14
22
 
15
- 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}}})
23
+ Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton copyWithZone:]: unrecognized selector sent to instance 0x14da0890'
24
+
25
+
26
+
27
+ libc++abi.dylib: terminating with uncaught exception of type NSException
16
28
 
17
29
  ```
18
30
 
@@ -28,7 +40,9 @@
28
40
 
29
41
  */
30
42
 
43
+ // 撮影する関数.
44
+
31
- func captureStillImage() {
45
+ func captureStillImage() {
32
46
 
33
47
 
34
48
 
@@ -68,12 +82,42 @@
68
82
 
69
83
  if error == nil {
70
84
 
71
- self.imageFromImageBuffer(imageBuffer!)
85
+
86
+
87
+ // imageFromImageBufferで取得したUIImageをJPEGに変換(これをDirectoryに保存).
88
+
89
+ let image = self.imageFromImageBuffer(imageBuffer!)
90
+
91
+ let JPEGdata = UIImageJPEGRepresentation(image!, 1)
92
+
93
+
94
+
95
+ // ドキュメントと保存先のパス.
96
+
97
+ let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(NSDate().description).jpeg")
98
+
99
+ print("書き込むファイルのパス: \(fileURL)")
100
+
101
+
102
+
103
+ // 保存処理.
104
+
105
+ do {
106
+
107
+ try JPEGdata?.write(to: fileURL, options: .atomic)
108
+
109
+ } catch {
110
+
111
+ print("保存に失敗:\(error)")
112
+
113
+ }
114
+
115
+ } else {
116
+
117
+ print("JPEG取得に失敗:\(error)")
72
118
 
73
119
  }
74
120
 
75
-
76
-
77
121
  })
78
122
 
79
123
  }
@@ -84,228 +128,132 @@
84
128
 
85
129
 
86
130
 
131
+ // imageBufferからUIImageに変換.
132
+
133
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? { // 調べる ImageBufferの型 1つにたくさんだったらそのまま送れる 1つに1枚なら指定しなきゃ
134
+
135
+
136
+
137
+ // imageBufferを確認.
138
+
139
+ if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
140
+
141
+
142
+
143
+ // 取得データのピクセル情報をロック.
144
+
145
+ CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
146
+
147
+
148
+
149
+ // ピクセルデータのパラメータ登場.
150
+
151
+ let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
152
+
153
+ let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
154
+
155
+ let width = CVPixelBufferGetWidth(imageBuffer)
156
+
157
+ let height = CVPixelBufferGetHeight(imageBuffer)
158
+
159
+ let colorSpace = CGColorSpaceCreateDeviceRGB()
160
+
161
+
162
+
163
+ // パラメータを載せる.
164
+
165
+ guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
166
+
167
+
168
+
169
+ // エラーの場合エラーを表示させる.
170
+
171
+ print("Couldn't create context for image.")
172
+
173
+ return nil
174
+
175
+ }
176
+
177
+
178
+
179
+ let quartzImage = context.makeImage()
180
+
181
+
182
+
183
+ // 取得データのピクセル情報をロック解除.
184
+
185
+ CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
186
+
187
+
188
+
189
+ // 取得した情報からUIImageとJPEGデータを作成.
190
+
191
+ if let quartzImage = quartzImage {
192
+
193
+
194
+
195
+ // UIImage.
196
+
197
+ let image = UIImage(cgImage: quartzImage)
198
+
199
+
200
+
201
+ return image
202
+
203
+ }
204
+
205
+ }
206
+
207
+ return nil
208
+
209
+ }
210
+
211
+
212
+
87
213
  /*
88
214
 
89
215
  アップロード開始ボタンのイベント.
90
216
 
91
217
  */
92
218
 
93
- // imageBufferからjpegに変換.
94
-
95
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
96
-
97
-
98
-
99
- // imageBufferを確認.
100
-
101
- if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
102
-
103
-
104
-
105
- // 取得データのピクセル情報をロック.
106
-
107
- CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
108
-
109
-
110
-
111
- // ピクセルデータのパラメータ登場.
112
-
113
- let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
114
-
115
- let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
116
-
117
- let width = CVPixelBufferGetWidth(imageBuffer)
118
-
119
- let height = CVPixelBufferGetHeight(imageBuffer)
120
-
121
- let colorSpace = CGColorSpaceCreateDeviceRGB()
122
-
123
-
124
-
125
- // パラメータを載せる.
126
-
127
- guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
128
-
129
-
130
-
131
- // エラーの場合エラーを表示させる.
132
-
133
- print("Couldn't create context for image.")
134
-
135
- return nil
136
-
137
- }
138
-
139
- let quartzImage = context.makeImage()
140
-
141
-
142
-
143
- // 取得データのピクセル情報をロック解除.
144
-
145
- CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
146
-
147
-
148
-
149
- // 取得した情報からUIImageとJPEGデータを作成.
150
-
151
- if let quartzImage = quartzImage {
152
-
153
-
154
-
155
- // UIImage.
156
-
157
- let image = UIImage(cgImage: quartzImage)
158
-
159
-
160
-
161
- // JPEGデータ.
162
-
163
- let imageJPEGdata = UIImageJPEGRepresentation(image, 1)
164
-
165
-
166
-
167
- // 通信のリクエスト生成.
168
-
169
- let uploadScriptUrl = NSURL(string:"http://localhost/*****/phpinfo.php")
170
-
171
- let request = NSMutableURLRequest(url: uploadScriptUrl! as URL)
172
-
173
- request.httpMethod = "POST"
174
-
175
- request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
176
-
177
- let configuration: URLSessionConfiguration = URLSessionConfiguration.default
178
-
179
- let session:URLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
180
-
181
-
182
-
183
-
184
-
185
- // アップロード用のタスクを生成.
186
-
187
- let task: URLSessionUploadTask = session.uploadTask(with: request as URLRequest, from: imageJPEGdata!) {
188
-
189
-
190
-
191
- data, response, error in
192
-
193
-
194
-
195
- if error != nil {
196
-
197
-
198
-
199
- print("error=\(error)")
200
-
201
-
202
-
203
- return
204
-
205
- }
206
-
207
- }
208
-
209
-
210
-
211
- // タスクの実行.
212
-
213
- task.resume()
214
-
215
-
216
-
217
- return image
218
-
219
- }
219
+ func tappedSentToServerButton(_ fileURL: NSData) {
220
+
221
+
222
+
223
+ // 通信のリクエスト生成.
224
+
225
+ let myCofig: URLSessionConfiguration = URLSessionConfiguration.default
226
+
227
+
228
+
229
+ let url:NSURL = NSURL(string: "http://*****.php")!
230
+
231
+
232
+
233
+ var request: URLRequest = URLRequest(url: url as URL)
234
+
235
+ request.httpMethod = "POST"
236
+
237
+
238
+
239
+ let session:URLSession = URLSession(configuration: myCofig, delegate: self, delegateQueue: OperationQueue.main)
240
+
241
+
242
+
243
+ let task:URLSessionUploadTask = session.uploadTask(with: request, from: fileURL as Data)
244
+
245
+
246
+
247
+ // タスクの実行.
248
+
249
+ task.resume()
250
+
251
+
252
+
253
+
220
254
 
221
255
  }
222
256
 
223
- return nil
224
-
225
- }
226
-
227
-
228
-
229
- /*
230
-
231
- 通信終了時に呼び出されるデリゲート.
232
-
233
- */
234
-
235
- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
236
-
237
- print("didCompleteWithError")
238
-
239
-
240
-
241
- // UIAlertControllerを作成する.
242
-
243
- let myAlert: UIAlertController = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert)
244
-
245
-
246
-
247
- // OKのアクションを作成する.
248
-
249
- let myOkAction = UIAlertAction(title: "OK", style: .default) { action in
250
-
251
- print("OK")
252
-
253
- }
254
-
255
-
256
-
257
- // OKのActionを追加する.
258
-
259
- myAlert.addAction(myOkAction)
260
-
261
-
262
-
263
- // UIAlertを発動する.
264
-
265
- present(myAlert, animated: true, completion: nil)
266
-
267
- }
268
-
269
-
270
-
271
- func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
272
-
273
-
274
-
275
- print("didSendBodyData")
276
-
277
- let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
278
-
279
- myProgress.progress = uploadProgress
280
-
281
- let progressPercent = Int(uploadProgress*100)
282
-
283
- myProgressLabel.text = "\(progressPercent)%"
284
-
285
- print(uploadProgress)
286
-
287
- }
288
-
289
-
290
-
291
- private func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
292
-
293
- print("didReceiveResponse")
294
-
295
- print(response);
296
-
297
-
298
-
299
- }
300
-
301
-
302
-
303
- func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
304
-
305
- print("didReceiveData")
306
-
307
- }
308
-
309
257
 
310
258
 
311
259
  ```
@@ -331,9 +279,3 @@
331
279
  ?>
332
280
 
333
281
  ```
334
-
335
-
336
-
337
- ###試したこと
338
-
339
- Info.plistに「NSAppTransportSecurity」をDictionaryで作成し、「NSAllowsArbitraryLoads」をBoolean型としてYESにしましたが、変わらずでした。

2

質問内容の編集

2017/06/30 13:45

投稿

fujico23
fujico23

スコア13

test CHANGED
@@ -1 +1 @@
1
- Swift:CoreDataに保存した画像データをPostgreSQLにアップロたい
1
+ カメラで取得した画像をPOST通信するとエラが出てまう
test CHANGED
@@ -1,26 +1,24 @@
1
1
  ###前提・実現したいこと
2
2
 
3
- iPhone cameraで撮影した写真をCoreDataに保存し、そのデータをPOST通信するアプリを作成しています。
4
-
5
- 撮影する能とそれをCoreDataに保存する機能実装できました。
6
-
7
-
8
-
9
- CoreDataに保存されたデータをPOST通信す際、そのデタはどのように定義したら良いでしょうか。
10
-
11
-
12
-
13
-
14
-
15
- ご教示お願いいたします。
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
- ###実装した部分のソースコード
3
+ iPhone cameraで撮影した写真をPOST通信するアプリを作成しています。
4
+
5
+ シミュレーションでビルド通りすが、撮影した瞬間にエラーが出てしまいます
6
+
7
+
8
+
9
+ ###発生してい問題・エラメッセージ
10
+
11
+
12
+
13
+ ```
14
+
15
+ 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}}})
16
+
17
+ ```
18
+
19
+
20
+
21
+ ###該当のソースコード
24
22
 
25
23
  ```Swift
26
24
 
@@ -32,12 +30,28 @@
32
30
 
33
31
  func captureStillImage() {
34
32
 
33
+
34
+
35
+ // 出力先が正しいことを確認.
36
+
35
37
  if let output = myImageOutput {
36
38
 
39
+
40
+
41
+ // キュー.
42
+
37
43
  DispatchQueue.global().async {
38
44
 
45
+
46
+
47
+ // 撮影の設定.
48
+
39
49
  let connection = output.connection(withMediaType: AVMediaTypeVideo)
40
50
 
51
+
52
+
53
+ // 撮影する露光時間を±2.0に設定.
54
+
41
55
  let settings = [-2.0, 0.0, 2.0].map {
42
56
 
43
57
  (bias: Float) -> AVCaptureAutoExposureBracketedStillImageSettings in
@@ -46,6 +60,10 @@
46
60
 
47
61
  }
48
62
 
63
+
64
+
65
+ // 撮影(キャプチャ取得).
66
+
49
67
  output.captureStillImageBracketAsynchronously(from: connection, withSettingsArray: settings, completionHandler: { (imageBuffer, settings, error) in
50
68
 
51
69
  if error == nil {
@@ -54,6 +72,8 @@
54
72
 
55
73
  }
56
74
 
75
+
76
+
57
77
  })
58
78
 
59
79
  }
@@ -66,16 +86,30 @@
66
86
 
67
87
  /*
68
88
 
69
- imageBufferをJPEGに変換
89
+ アップロード開始ボタンのイベント.
70
90
 
71
91
  */
72
92
 
93
+ // imageBufferからjpegに変換.
94
+
73
- func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
95
+ func imageFromImageBuffer(_ sampleBuffer: CMSampleBuffer) -> UIImage? {
96
+
97
+
98
+
99
+ // imageBufferを確認.
74
100
 
75
101
  if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
76
102
 
103
+
104
+
105
+ // 取得データのピクセル情報をロック.
106
+
77
107
  CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
78
108
 
109
+
110
+
111
+ // ピクセルデータのパラメータ登場.
112
+
79
113
  let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
80
114
 
81
115
  let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
@@ -86,12 +120,16 @@
86
120
 
87
121
  let colorSpace = CGColorSpaceCreateDeviceRGB()
88
122
 
123
+
124
+
89
-
125
+ // パラメータを載せる.
90
126
 
91
127
  guard let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else {
92
128
 
93
129
 
94
130
 
131
+ // エラーの場合エラーを表示させる.
132
+
95
133
  print("Couldn't create context for image.")
96
134
 
97
135
  return nil
@@ -102,6 +140,8 @@
102
140
 
103
141
 
104
142
 
143
+ // 取得データのピクセル情報をロック解除.
144
+
105
145
  CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
106
146
 
107
147
 
@@ -112,49 +152,65 @@
112
152
 
113
153
 
114
154
 
155
+ // UIImage.
156
+
115
157
  let image = UIImage(cgImage: quartzImage)
116
158
 
159
+
160
+
161
+ // JPEGデータ.
162
+
117
163
  let imageJPEGdata = UIImageJPEGRepresentation(image, 1)
118
164
 
119
-
120
-
121
-
122
-
165
+
166
+
123
- /*
167
+ // 通信のリクエスト生成.
124
-
168
+
125
- JPEGをCoreDataに保存
169
+ let uploadScriptUrl = NSURL(string:"http://localhost/*****/phpinfo.php")
126
-
127
- */
170
+
128
-
129
- let appDel: AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
171
+ let request = NSMutableURLRequest(url: uploadScriptUrl! as URL)
172
+
130
-
173
+ request.httpMethod = "POST"
174
+
131
-
175
+ request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
132
-
176
+
133
- let context: NSManagedObjectContext = appDel.managedObjectContext
177
+ let configuration: URLSessionConfiguration = URLSessionConfiguration.default
134
-
135
-
136
-
178
+
137
- let myEntity: NSEntityDescription! = NSEntityDescription.entity(forEntityName: "MyCoreDataStore", in: context)
179
+ let session:URLSession = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
180
+
181
+
182
+
183
+
184
+
138
-
185
+ // アップロード用のタスクを生成.
139
-
140
-
186
+
141
- let newData = MyCoreDataStore(entity: myEntity, insertInto: context)
187
+ let task: URLSessionUploadTask = session.uploadTask(with: request as URLRequest, from: imageJPEGdata!) {
188
+
189
+
190
+
142
-
191
+ data, response, error in
192
+
193
+
194
+
143
-
195
+ if error != nil {
144
-
145
-
146
-
196
+
197
+
198
+
147
- newData.photo = imageJPEGdata as NSData?
199
+ print("error=\(error)")
200
+
201
+
202
+
148
-
203
+ return
204
+
205
+ }
206
+
207
+ }
208
+
209
+
210
+
211
+ // タスクの実行.
212
+
149
- newData.time = NSDate()
213
+ task.resume()
150
-
151
-
152
-
153
- (UIApplication.shared.delegate as! AppDelegate).saveContext()
154
-
155
-
156
-
157
-
158
214
 
159
215
 
160
216
 
@@ -162,172 +218,122 @@
162
218
 
163
219
  }
164
220
 
165
-
166
-
167
221
  }
168
222
 
169
223
  return nil
170
224
 
171
225
  }
172
226
 
227
+
228
+
229
+ /*
230
+
231
+ 通信終了時に呼び出されるデリゲート.
232
+
233
+ */
234
+
235
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
236
+
237
+ print("didCompleteWithError")
238
+
239
+
240
+
241
+ // UIAlertControllerを作成する.
242
+
243
+ let myAlert: UIAlertController = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert)
244
+
245
+
246
+
247
+ // OKのアクションを作成する.
248
+
249
+ let myOkAction = UIAlertAction(title: "OK", style: .default) { action in
250
+
251
+ print("OK")
252
+
253
+ }
254
+
255
+
256
+
257
+ // OKのActionを追加する.
258
+
259
+ myAlert.addAction(myOkAction)
260
+
261
+
262
+
263
+ // UIAlertを発動する.
264
+
265
+ present(myAlert, animated: true, completion: nil)
266
+
267
+ }
268
+
269
+
270
+
271
+ func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
272
+
273
+
274
+
275
+ print("didSendBodyData")
276
+
277
+ let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
278
+
279
+ myProgress.progress = uploadProgress
280
+
281
+ let progressPercent = Int(uploadProgress*100)
282
+
283
+ myProgressLabel.text = "\(progressPercent)%"
284
+
285
+ print(uploadProgress)
286
+
287
+ }
288
+
289
+
290
+
291
+ private func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveResponse response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
292
+
293
+ print("didReceiveResponse")
294
+
295
+ print(response);
296
+
297
+
298
+
299
+ }
300
+
301
+
302
+
303
+ func urlSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
304
+
305
+ print("didReceiveData")
306
+
307
+ }
308
+
173
309
 
174
310
 
175
311
  ```
176
312
 
313
+ ```php
314
+
315
+ <?php
316
+
317
+
318
+
319
+ // リクエストBodyからファイルのデータを保存
320
+
321
+ $image = file_get_contents("php://input");
322
+
323
+
324
+
325
+ // 受け取った値の表示
326
+
327
+ echo $_POST;
328
+
329
+
330
+
331
+ ?>
332
+
333
+ ```
334
+
177
335
 
178
336
 
179
337
  ###試したこと
180
338
 
181
- 以下がCoreDataに保存されたデータをPOST通信する部分のコードです。
182
-
183
- ```swift
184
-
185
-
186
-
187
- /*
188
-
189
-
190
-
191
- ここでCoreData内のデータを定義するのではないかと考えています。
192
-
193
- /*
194
-
195
-
196
-
197
-
198
-
199
- let url = NSURL(string: "http://****.php")
200
-
201
- let urlRequest: NSMutableURLRequest = NSMutableURLRequest()
202
-
203
-
204
-
205
- if let u = url {
206
-
207
-
208
-
209
- urlRequest.url = u as URL
210
-
211
- urlRequest.httpMethod = "POST"
212
-
213
-
214
-
215
-
216
-
217
- }
218
-
219
-
220
-
221
-
222
-
223
- let uniqueId = ProcessInfo.processInfo.globallyUniqueString
224
-
225
- let body: NSMutableData = NSMutableData()
226
-
227
- var postData: String = String()
228
-
229
- let boundary: String = "---------------------------\(uniqueId)"
230
-
231
-
232
-
233
-
234
-
235
-
236
-
237
- urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
238
-
239
-
240
-
241
- postData += "--\(boundary)\r\n"
242
-
243
-
244
-
245
-
246
-
247
- postData += "Content-Disposition: form-data; name=\"image\"; filename=\"images.jpg\"\r\n"
339
+ Info.plistに「NSAppTransportSecurity」をDictionaryで作成し、「NSAllowsArbitraryLoads」をBoolean型としてYESにしましたが、変わらずでした。
248
-
249
- postData += "Content-Type: image/jpeg\r\n\r\n"
250
-
251
- body.append(postData.data(using: String.Encoding.utf8)!)
252
-
253
- body.append(file as Data)
254
-
255
-
256
-
257
- postData = String()
258
-
259
- postData += "\r\n"
260
-
261
- postData += "\r\n--\(boundary)--\r\n"
262
-
263
-
264
-
265
-
266
-
267
- body.append(postData.data(using: String.Encoding.utf8)!)
268
-
269
-
270
-
271
- urlRequest.httpBody = NSData(data: body as Data) as Data
272
-
273
- print(urlRequest)
274
-
275
-
276
-
277
- // send request and recieve response
278
-
279
- let config = URLSessionConfiguration.default
280
-
281
- let session = URLSession(configuration: config)
282
-
283
-
284
-
285
- let task: URLSessionDataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { data, request, error in
286
-
287
-
288
-
289
- // reterned data from serverSide
290
-
291
- let result = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
292
-
293
- print("result=\(result)")
294
-
295
-
296
-
297
- })
298
-
299
- task.resume()
300
-
301
-
302
-
303
-
304
-
305
- }
306
-
307
-
308
-
309
- ```
310
-
311
-
312
-
313
- ```php
314
-
315
- <?php
316
-
317
-
318
-
319
- // リクエストBodyからファイルのデータを保存
320
-
321
- $image = file_get_contents("php://input");
322
-
323
-
324
-
325
- // 受け取った値の表示
326
-
327
- echo $_POST;
328
-
329
-
330
-
331
- ?>
332
-
333
- ```

1

具体化

2017/06/28 06:08

投稿

fujico23
fujico23

スコア13

test CHANGED
File without changes
test CHANGED
@@ -1,12 +1,12 @@
1
1
  ###前提・実現したいこと
2
2
 
3
- アイフォンカメラで撮影した写真をCoreDataに保存し、そのデータをPostgreSQLにアップロードするアプリを作成しています。
3
+ iPhone cameraで撮影した写真をCoreDataに保存し、そのデータをPOST通信するアプリを作成しています。
4
4
 
5
5
  撮影する機能と、それをCoreDataに保存する機能は実装できました。
6
6
 
7
7
 
8
8
 
9
- 具体的にCoreDataデータをPostgreSQLにアップロードするためにはどうすればよいでしょうか。
9
+ CoreDataに保存されたデータをPOST通信する際、そのデータはどのよに定義したら良いでしょうか。
10
10
 
11
11
 
12
12
 
@@ -178,206 +178,132 @@
178
178
 
179
179
  ###試したこと
180
180
 
181
- まず、ApacheおよびPHPファイルをMacインストルしました
181
+ 以下がCoreData保存されたデタをPOST通信する部分のコードです
182
-
183
- その後今回開発したいアプリとは別のアプリを練習として作成し、画像をApacheに通信するコードを書いてみました。
184
182
 
185
183
  ```swift
186
184
 
185
+
186
+
187
+ /*
188
+
189
+
190
+
191
+ ここでCoreData内のデータを定義するのではないかと考えています。
192
+
193
+ /*
194
+
195
+
196
+
197
+
198
+
199
+ let url = NSURL(string: "http://****.php")
200
+
201
+ let urlRequest: NSMutableURLRequest = NSMutableURLRequest()
202
+
203
+
204
+
187
- import UIKit
205
+ if let u = url {
206
+
207
+
208
+
188
-
209
+ urlRequest.url = u as URL
210
+
189
-
211
+ urlRequest.httpMethod = "POST"
212
+
213
+
214
+
215
+
216
+
190
-
217
+ }
218
+
219
+
220
+
221
+
222
+
191
- class ViewController: UIViewController, URLSessionTaskDelegate {
223
+ let uniqueId = ProcessInfo.processInfo.globallyUniqueString
224
+
192
-
225
+ let body: NSMutableData = NSMutableData()
193
-
194
-
226
+
195
- var json: NSData!
227
+ var postData: String = String()
228
+
196
-
229
+ let boundary: String = "---------------------------\(uniqueId)"
230
+
231
+
232
+
233
+
234
+
235
+
236
+
197
-
237
+ urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
238
+
239
+
240
+
198
-
241
+ postData += "--\(boundary)\r\n"
242
+
243
+
244
+
245
+
246
+
199
-
247
+ postData += "Content-Disposition: form-data; name=\"image\"; filename=\"images.jpg\"\r\n"
248
+
200
-
249
+ postData += "Content-Type: image/jpeg\r\n\r\n"
250
+
251
+ body.append(postData.data(using: String.Encoding.utf8)!)
252
+
201
- override func viewDidLoad() {
253
+ body.append(file as Data)
202
-
254
+
255
+
256
+
203
- super.viewDidLoad()
257
+ postData = String()
258
+
204
-
259
+ postData += "\r\n"
260
+
205
-
261
+ postData += "\r\n--\(boundary)--\r\n"
262
+
263
+
264
+
265
+
266
+
206
-
267
+ body.append(postData.data(using: String.Encoding.utf8)!)
268
+
269
+
270
+
271
+ urlRequest.httpBody = NSData(data: body as Data) as Data
272
+
273
+ print(urlRequest)
274
+
275
+
276
+
277
+ // send request and recieve response
278
+
279
+ let config = URLSessionConfiguration.default
280
+
281
+ let session = URLSession(configuration: config)
282
+
283
+
284
+
285
+ let task: URLSessionDataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { data, request, error in
286
+
287
+
288
+
289
+ // reterned data from serverSide
290
+
291
+ let result = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
292
+
293
+ print("result=\(result)")
294
+
295
+
296
+
297
+ })
298
+
207
- upload()
299
+ task.resume()
300
+
301
+
208
302
 
209
303
 
210
304
 
211
305
  }
212
306
 
213
-
214
-
215
- func upload() {
216
-
217
-
218
-
219
- let sampleImage = UIImage(named: "myimage.jpg")
220
-
221
- let file: NSData = NSData(data: UIImageJPEGRepresentation(sampleImage!, 1.0)!)
222
-
223
-
224
-
225
- let url = NSURL(string: "http://********.php")
226
-
227
- let urlRequest: NSMutableURLRequest = NSMutableURLRequest()
228
-
229
-
230
-
231
- if let u = url {
232
-
233
-
234
-
235
- urlRequest.url = u as URL
236
-
237
- urlRequest.httpMethod = "POST"
238
-
239
- // urlRequest.timeoutInterval = 30.0
240
-
241
-
242
-
243
- }
244
-
245
-
246
-
247
-
248
-
249
- let uniqueId = ProcessInfo.processInfo.globallyUniqueString
250
-
251
- let body: NSMutableData = NSMutableData()
252
-
253
- var postData: String = String()
254
-
255
- let boundary: String = "---------------------------\(uniqueId)"
256
-
257
-
258
-
259
-
260
-
261
-
262
-
263
- urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
264
-
265
-
266
-
267
- postData += "--\(boundary)\r\n"
268
-
269
-
270
-
271
-
272
-
273
- postData += "Content-Disposition: form-data; name=\"image\"; filename=\"images.jpg\"\r\n"
274
-
275
- postData += "Content-Type: image/jpeg\r\n\r\n"
276
-
277
- body.append(postData.data(using: String.Encoding.utf8)!)
278
-
279
- body.append(file as Data)
280
-
281
-
282
-
283
- postData = String()
284
-
285
- postData += "\r\n"
286
-
287
- postData += "\r\n--\(boundary)--\r\n"
288
-
289
-
290
-
291
-
292
-
293
- body.append(postData.data(using: String.Encoding.utf8)!)
294
-
295
-
296
-
297
- urlRequest.httpBody = NSData(data: body as Data) as Data
298
-
299
- print(urlRequest)
300
-
301
-
302
-
303
-
304
-
305
- let config = URLSessionConfiguration.default
306
-
307
- let session = URLSession(configuration: config)
308
-
309
-
310
-
311
- let task: URLSessionDataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { data, request, error in
312
-
313
-
314
-
315
-
316
-
317
- let result = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
318
-
319
- print("result=\(result)")
320
-
321
-
322
-
323
- })
324
-
325
- task.resume()
326
-
327
-
328
-
329
- }
330
-
331
-
332
-
333
-
334
-
335
- //通信終了時に呼び出されるデリゲート
336
-
337
- func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
338
-
339
- // print("didCompleteWithError")
340
-
341
- print("error: \(error)")
342
-
343
-
344
-
345
- }
346
-
347
-
348
-
349
- func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
350
-
351
- print("willPerformHTTPRedirection")
352
-
353
- }
354
-
355
-
356
-
357
- func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
358
-
359
- print("didSendBodyData")
360
-
361
- }
362
-
363
-
364
-
365
-
366
-
367
- override func didReceiveMemoryWarning() {
368
-
369
- super.didReceiveMemoryWarning()
370
-
371
- // Dispose of any resources that can be recreated.
372
-
373
- }
374
-
375
-
376
-
377
-
378
-
379
- }
380
-
381
307
 
382
308
 
383
309
  ```
@@ -405,9 +331,3 @@
405
331
  ?>
406
332
 
407
333
  ```
408
-
409
-
410
-
411
- ###補足情報(言語/FW/ツール等のバージョンなど)
412
-
413
- 記載したコードで間違っている箇所があればご指摘頂けると幸いです。