swift サーバへPOST送信のimage無しとimage有りの処理

image無しのpost送信

```swift
    func myMessageUploadRequest(){
        var url = URL(string:  "http://受取処理.php");
        print(url)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        var req = NSMutableURLRequest(url: url!)
        var token = "lastName=\(commentText.text!)&TypeName=Message&groupid="+textgid+"&userId="+userid!
        req.httpMethod = "POST"
        req.httpBody = token.data(using: String.Encoding.utf8)
        var task = session.dataTask(with: req as URLRequest, completionHandler: {
            (data, resp, err) in
            print(resp!.url!)
            print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
        })
        task.resume()
    }
```

//multipart利用例

```swift
    func myMessageUploadRequest(){
        let myUrl = URL(string: "送信先url");
        let request = NSMutableURLRequest(url:myUrl!);
        request.httpMethod = "POST";        
        let param = [
            "sendid"  : id.text!,
            "sendtext"  : "textdata.text!"
        ]
        
        let boundary = generateBoundaryString()
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        request.httpBody = createBodyWithParameters2(param, filePathKey: "file", boundary: boundary)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            if error != nil {
                print("error=\(error)")
                return
            }
            // レスポンスを出力
            print("******* response = \(response)")
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")
            
            DispatchQueue.main.async(execute: {
                //アップロード完了
                self.id.text = ""
                self.textdata.text = ""
            });
        }
        task.resume()
    }
    
    func createBodyWithParameters2(_ parameters: [String: String]?, filePathKey: String?, boundary: String) -> Data {
        let body = NSMutableData();
        print("ok4")
        
        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }
        body.appendString("--\(boundary)\r\n")
        body.appendString("\r\n")
        body.appendString("--\(boundary)--\r\n")
        
        return body as Data
    }
```

image有りの場合

```swift
    func myImageUploadRequest(){
        print(globalmainurl)
        let myUrl = URL(string: globalmainurl! + "/swift_receive_app.php");
        let request = NSMutableURLRequest(url:myUrl!);
        request.httpMethod = "POST";
        print("ok2xxxx"+globalauthid!+globalmainurl! + "/swift_receive_app.php")
        
        let param = [
            "groupid"  : textgid,
            "firstName"  : "Message",
            "lastName"    : commentText.text!,
            "userId"    : globalauthid!
        ]
        
        let boundary = generateBoundaryString()
        
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        
        let imageData = UIImageJPEGRepresentation(ImageView.image!, 0.5)
        
        if(imageData==nil)  {
            print("error")
            return;
        }
        print("ok3")
        
        request.httpBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            if error != nil {
                print("error=\(error)")
                return
            }
            // レスポンスを出力
            print("******* response = \(response)")
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")
            
            DispatchQueue.main.async(execute: {
                //アップロード完了
                self.ImageView.image = nil;
            });
        }
        task.resume()     
    }
    
    func createBodyWithParameters(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
        let body = NSMutableData();
        print("ok4")
        
        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }
        let filename = "user-profile.jpg"
        
        let mimetype = "image/jpg"
        
        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.append(imageDataKey)
        body.appendString("\r\n")
        body.appendString("--\(boundary)--\r\n")
        
        return body as Data
    }
    
    func generateBoundaryString() -> String {
        return "Boundary-\(UUID().uuidString)"
    }
```