[英]access the web service and send data using iOS Objective C
我有字符串對象和圖像存儲在nsdata中。 如何通過訪問URL將其發送到服務器? 我看過例子。但是它不起作用。有人可以提前告訴我謝謝!!
AFNetworking是做到這一點的最佳方法。 而且那里有很多教程。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"username": _username.text,
@"password": passwordMD5
};
[manager POST:@"http://example.com/ws/test.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject); //This is the Response
}else{
//if you didnt get expected output then handle it here
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
//Handle any network errors here. ex: if internet disconnected.
}];
這是一個示例,說明如何使用AFNetworking將帶有字符串對象的圖像作為字典上載到服務器。
- (void)uploadPhoto {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://server.url"]];
NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
NSDictionary *parameters = @{@"username": self.username, @"password" : self.password};
AFHTTPRequestOperation *op = [manager POST:@"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:paramNameForImage fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[op start];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.