Objective-c - 将图像上传到服务器和两个字符串并读回响应

时间:2017-08-14 06:15:06

标签: php objective-c json xcode

我花了一生的时间在互联网上搜索如何使用带有2个字符串的Objective-c将图像上传到服务器以及如何处理JSON响应。

因此,在这个应用程序中,您选择一张照片,然后按下按钮将其上传到PHP服务器,该请求还包括2个必须处理的字符串。请求是POST。

问题在于,而不是接收诸如"成功"之类的消息。或"崩溃"从我的JSON,我收到的内容如下:< 6e6f5f72 65717565 7374>

Objective-c代码示例(网址因安全原因而受到审查)。

// Convert photo to string
            NSString *photoString = [UIImagePNGRepresentation(chosenImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

            // Crypt ID, photo and magic hashtag
            // Create NSData objects
            NSData *dataIDSession2PP = [IDSessionPP dataUsingEncoding: NSUTF8StringEncoding];
            NSData *dataPhotot2PP= [photoString dataUsingEncoding: NSUTF8StringEncoding];
            NSData *dataMagic2PP = [magicString7 dataUsingEncoding: NSUTF8StringEncoding];

            // Get NSString from NSData object in Base64
            NSString *IDSessionEncode2PP = [dataIDSession2PP base64EncodedStringWithOptions:0];
            NSString *photoEncode2PP = [dataPhotot2PP base64EncodedStringWithOptions:0];
            NSString *magicEncode2PP = [dataMagic2PP base64EncodedStringWithOptions:0];

            // Prepare request for server
            NSURL *uploadPhotoURL = [NSURL URLWithString:@"https://www.***************.com/photo.php"];
            NSMutableURLRequest *uploadPhotoRequest = [NSMutableURLRequest requestWithURL:uploadPhotoURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
            [uploadPhotoRequest setHTTPMethod:@"POST"];
            NSMutableData *body = [NSMutableData data];
            NSString *boundary = @"---------------------------14737809831466499882746641449";
            NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
            [uploadPhotoRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];

            // Profile photo
            NSData *imageData = UIImageJPEGRepresentation(chosenImage, 90);
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Disposition: attachment; name=\"image_data\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithData:imageData]];
            [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

            // User session ID
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"member\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithString: IDSessionEncode2PP] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

            // Magic string
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"kkkkarondi\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithString: magicEncode2PP] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

            // Close form
            [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

            // Set request body
            [uploadPhotoRequest setHTTPBody:body];

            // Get PHP server response
            NSURLSession *updateProfileSession = [NSURLSession sharedSession];
            NSURLSessionDataTask *dataTask = [updateProfileSession dataTaskWithRequest:uploadPhotoRequest completionHandler:^(NSData *uploadPhotoData, NSURLResponse *uploadPhotoResponse, NSError *uploadPhotoError) {
                // Console
                NSLog(@"Server data: %@", uploadPhotoData);
                NSLog(@"Server repsonse: %@", uploadPhotoResponse);
                NSLog(@"Server error: %@", uploadPhotoError);

                // Check HTTP response
                NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)uploadPhotoResponse;
                if (HTTPResponse.statusCode == 200) {
                    // Valid status code
                    // Check if any errors
                    if (uploadPhotoError != nil) {
                        // Error found
                        // Show alert message
                        UIAlertController *alert =[ UIAlertController alertControllerWithTitle:@"App Name" message: @"We could not upload your photo, please try again." preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *OKButton = [UIAlertAction actionWithTitle: @"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                            // Do nothing
                        }];
                        [alert addAction: OKButton];
                        [self presentViewController:alert animated:YES completion:nil];
                    } else {
                        // No errors
                        // Console
                        NSLog(@"No errors found");

                        // Convert data response to dictionary
                        NSDictionary *uploadPhotoDictionary = [NSJSONSerialization JSONObjectWithData:uploadPhotoData options:0 error:&uploadPhotoError];

                        NSLog(@"Dictionary: %@", uploadPhotoDictionary);

                        // Handle messages
                        /*if () {
                            // Success

                        } else if () {
                            // Database

                        } else if () {
                            // Crash

                        } else if () {
                            // Upload failed

                        } else if () {
                            // Missing values

                        } else if () {
                            // Invalid member

                        } else {
                            // Unknown error
                        }*/


                    }
                } else {
                    // Something went wrong
                    // Show alert message
                    UIAlertController *alert =[ UIAlertController alertControllerWithTitle:@"App Name" message: @"Something went wrong while uploading your photo, please try again." preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *OKButton = [UIAlertAction actionWithTitle: @"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                        // Do nothing
                    }];
                    [alert addAction: OKButton];
                    [self presentViewController:alert animated:YES completion:nil];

                    // Console
                    NSLog(@"Wrong status code: %ld", (long)HTTPResponse.statusCode);
                }
            }];

            // Send the request
            [dataTask resume];

PHP代码示例

<?php

// some secret code goes here

if (isset($_POST['image_data'])) {
    // Get POST values
    $member_ID = base64_decode($_POST['member']);
    $member_ID = base64_decode($_POST['image_data']);
    $member_ID = md5(base64_decode($_POST['kkkarondi']));
} else {
    // No request
    echo "no_hashtag";
    exit();
}


// Handle various cases and echo messages


?>

那么如何在Objective-c中处理&#34; echo&#34;?

返回的消息

提前谢谢!

0 个答案:

没有答案