I try do POST request to backend server and use this for base session inside of a class "ServiceUtils" in objective - c
(AFHTTPSessionManager *)baseSessionManager {
if (httpSessionManager) {
return httpSessionManager;
}
httpSessionManager = [AFHTTPSessionManager manager];
httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
[httpSessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[httpSessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// User agent for iOS app.
NSString *userAgent = [NSString stringWithFormat:#"xxxxx Mobile iOS/%# (%# - %# v%#)", [Utils appVersionWithBuild], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion]];
[httpSessionManager.requestSerializer setValue:userAgent forHTTPHeaderField:#"User-Agent"];
// Mobile auth
User *user = [User getUserWithContext:[NSManagedObjectContext MR_defaultContext]];
NSString *mobileAuth = [[NSString stringWithFormat:#"%#--givemymoneybackdude", user.token] sha1];
[httpSessionManager.requestSerializer setValue:mobileAuth forHTTPHeaderField:#"Mobile-Auth"];
// Authorization
NSString *authorization = [[NSString stringWithFormat:#"%#:X", user.token] stringBase64];
[httpSessionManager.requestSerializer setValue:[NSString stringWithFormat:#"Basic %#", authorization] forHTTPHeaderField:#"Authorization"];
// Locale
if (user.locale) {
[httpSessionManager.requestSerializer setValue:user.locale forHTTPHeaderField:#"Accept-Language"];
}
return httpSessionManager;
}
Here is my code to try make POST request in swift 2.3
if let url = NSURL(string: "xxxxxxxx") {
let session = ServicesUtils.baseSessionManager()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])
session.dataTaskWithRequest(request) { data, response, error in
guard
error == nil &&
(response as? NSHTTPURLResponse)?.statusCode == 200
else {
print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
print(error?.localizedDescription ?? "no error description")
return
}
}.resume()
After try this i get this error :
Request failed: unauthorized (401)
I checked the header and it is ok but this problem is occurring. Can someone tell me why it's happening? And how could I pass inside a jsonObject a dictionary called "Integration" containing the values in it
This Code will help You…And using Alamofire.
Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
if(response.result.error == nil){
if((response.response?.statusCode)! < 500){
if(response.response?.statusCode == 200){
if let JSON = response.result.value {
let dict = JSON as! NSDictionary
let status :Bool = dict["status"] as! Bool
if(status){
success(dict)
}else{
failure(dict["message"] as! String)
}
}
}else{
failure("Something went wrong please try again")
}
}else{
failure("Something went wrong please try again")
}
}
}
}
I hope the following Link will may help you: https://github.com/Alamofire/Alamofire
Related
I have an application which implements remote notifications via firebase messaging api. In this app, I have implemented a notification service extension, which among others, implement UNNotificationActions.
In one of these actions, I've implemented an input field where you can write something, which then should be posted to firestore.
I've tried implementing this, but without success. So my question is how can I write to firestore from a rich notification running in the background - is this even possible?
My implementation looks like this:
let likeAction = UNNotificationAction(identifier: "likeAction", title: "Like", options: [])
let commentAction = UNTextInputNotificationAction(identifier: "commentAction", title: "Comment", options: [UNNotificationActionOptions.authenticationRequired], textInputButtonTitle: "Send", textInputPlaceholder: "Type your message")
let category = UNNotificationCategory(identifier: "posts", actions: [likeAction, commentAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
Then in AppDelegate, I implement the function to run whenever this is triggered like this:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
switch response.actionIdentifier {
case "commentAction":
guard let data = response.notification.request.content.userInfo["data"] as? [String: Any] else { return }
guard
let channelName = data["channelName"],
let postId = data["postId"]
else { return }
if let message = response as? UNTextInputNotificationResponse {
let documentPath = "\(channelName)/\(postId))"
let post = Post()
post.documentPath = documentPath
post.addComment(text: message.userText, postDocumentPath: documentPath)
}
I've debugged the code, and the method post.addComment() does actually get fired, and every field has a value. When I check the database, nothing gets inserted into it. The console prints out this, which I don't know if is related to the problem, I haven't been able to find anything online about these lines:
dnssd_clientstub deliver_request ERROR: write_all(21, 65 bytes) failed
nssd_clientstub read_all(26) DEFUNCT
When running the post method, no error from firebase comes up.
This was the initial information I could think of. I can provide more code or info if need be.
Update
I've discovered if I press the button while on lock screen, but with the iPhone in an unlocked state, nothing happens - as soon as I swipe up, and the app shows, the request gets send. This does indeed seem to be a background issue.
Kind regards Chris
So I finally found a solution / workaround.
It turns out that firebase will not post in the background, instead it stores the data locally, until the app comes into foreground, then it will post it.
The solution was to add another firebase function that listens for HTTP requests. In this function, I added a method to post to the database with the data from the action.
I then do a regular but modified http post request with Alamofire from the action to the url like this:
let headers: HTTPHeaders = [
"Authorization": "Bearer \(token)",
"Content-Type": "application/json"
]
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 15.0
configuration.timeoutIntervalForResource = 15.0
configuration.waitsForConnectivity = true
self.alamofireManager = Alamofire.SessionManager(configuration: configuration)
guard let manager = self.alamofireManager else {
return
}
manager.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseString(completionHandler: { (response) in
let _ = manager
print(response)
closure(true)
})
The important part of this, for me, was to set configuration.waitsForConnectivity = true otherwise, it would come back saying no connection to the internet.
This enables the function to comment on a notification from the lock screen.
Hope this information helps others looking for the same.
For anyone using a standard NSURLSession to complete the firestore HTTP REST request (and not Alamofire like in #ChrisEenberg's excellent answer above)
[NB: A previous version of this answer used background tasks, which are not necessary. This edit uses an ordinary NSURLSessionDataTask upload task and appears to work when app is backgrounded or closed, as expected.]
OBJECTIVE-C
Inside didReceiveNotificationResponse:
Prepare request
// Grab authenticated firestore user
FIRUser *db_user = [FIRAuth auth].currentUser;
// Set up the response
NSDictionary *reqFields;
// Fields for firestore object (REST API)
NSDictionary *my_uid_val = [[NSDictionary alloc] initWithObjectsAndKeys: (db_user.uid ?: [NSNull null]), (db_user.uid ? #"stringValue" : #"nullValue"), nil];
NSDictionary *action_val = [[NSDictionary alloc] initWithObjectsAndKeys: response.actionIdentifier, (response.actionIdentifier ? #"stringValue" : #"nullValue"), nil];
// Create object
reqFields = #{
#"my_uid": my_uid_val,
#"action": action_val
};
// Place fields into expected reqBody format (i.e. under 'fields' property)
NSDictionary *reqBody = [[NSDictionary alloc] initWithObjectsAndKeys:
reqFields, #"fields",
nil];
// Confirm...?
NSLog(#"%#", reqBody);
Compose the request
// Grab current user's token (for authenticated firestore REST API call)
[db_user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
if (!error && token) {
NSLog(#"Successfully obtained getIDTokenWithCompletion: %#", token);
// Compose stringified response
// + (per https://stackoverflow.com/a/44923210/1183749 )
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:reqBody options:kNilOptions error:&error];
if(!postData){
NSLog(#"Error creating JSON: %#", [error localizedDescription]);
}else{
NSLog(#"Successfully created JSON.");
}
// Create the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://firestore.googleapis.com/v1beta1/projects/%#/databases/%#/documents/%#", #"project_id", #"(default)", #"collection_id"]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"Bearer %#", token] forHTTPHeaderField:#"Authorization"]; // 'token' is returned in [[FIRAuth auth].currentUser getIDTokenWithCompletion]. (All of this code resides inside the getIDTokenWithCompletion block so we can pass it along with the request and let firebase security rules take care of authenticating the request.)
[request setHTTPBody:postData];
// Set up the session configuration
NSURLSessionConfiguration *sessionConfig;
sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
// Set up the session
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
Start the upload task
// Start the upload task
NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *uploadTaskResp, NSError *error) {
NSLog(#"dataTask Request reply: %#", uploadTaskResp);
if(error){
NSLog(#"dataTask Request error: %#", error);
}
// Call completion handler
completionHandler();
}
}
}
I'm trying to read remote txt file, which is located at remote hosting. I have a link, like http://www.link.com/file.txt.
I am using this code:
let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOfURL: myURL)
print("HTML : \(myHTMLString)")
} catch let error as NSError {
print("Error: \(error)")
}
But always getting empty string. File is not empty for sure.
I'm running my app on iOS simulator in Xcode.
What am I doing wrong?
Sorry for my bad English.
Don't use stringWithContentsOfURL and friends to retrieve data from a remote server. That's a synchronous API that was designed solely for use with local files. It isn't even guaranteed to work right for network requests on background threads, much less in your main thread.
The right way to retrieve data from remote URLs is with NSURLSession. I'm not a Swift programmer, so I'm not going to attempt a Swift snippet, but the Objective-C equivalent is:
NSURL *url = ...
NSURLSessionDataTask *task =
[NSURLSession sharedSession dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
// Handle client-side errors here
} else if (((NSHTTPURLResponse *)response).statusCode != 200) {
// Handle server-side errors here
} else {
NSString *stock = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Do something with data here.
}
}];
[task resume];
Haven't test the code, but this should lead you on the right direction.
var statsRequest: String = "http://www.link.com/file.txt"
var statsRequestURL: NSURL = NSURL(string: statsRequest)!
var error: NSError? = nil
var stockNews: String = try! String.stringWithContentsOfURL(statsRequestURL, encoding: NSUTF8StringEncoding)
If the text file has a different encoding you can just use NSASCIIStringEncoding and then parse the html file.
Is it possible to share a video using SLRequest ?
I'm able to share Images using the same
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message];
if (isImage)
{
NSData *data = UIImagePNGRepresentation(imgSelected);
[postRequest addMultipartData:data withName:#"media" type:#"image/png" filename:#"TestImage.png"];
}
postRequest.account = account;
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if (!error)
{
NSLog(#"Upload Sucess !");
}
}];
I have been reading through the Twitter Video upload API documentation and its really pretty simple. You basically need to make 3 POST requests to their API. The video you are uploading is also limited to 15 MB in size.
Uploads using this endpoint require at least 3 calls, one to
initialize the request, which returns the media_id, one or more calls
to append/upload binary or base64 encoded data, and one last call to
finalize the upload and make the media_id usable with other resources.
So it works like this:
Request 1: Send a init request with the video size in bytes. This will return a Media ID number which we have to use in request 2 and 3.
Request 2: Use the returned Media ID number from request 1 to upload the video data.
Request 3: Once the video upload has finished, send a "FINALIZE" request back to the Twitter API. This lets the Twitter API know that all the chunks of the video file has finished uploading.
Note The Twitter API accepts video uploads in "chunks". So if your video file is quite big, you may want to split it up into more than one file and thus you will have to repeat "Request 2" more than once (not forgetting to increment the "segment_index" number each time).
I have had a go at coding this below. Try it and experiment around with it. I will update my answer later on to improve it too.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
// Check the media type string so we can determine if its a video
if ([mediaType isEqualToString:#"public.movie"]) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
// Get the size of the file in bytes.
NSString *yourPath = [NSString stringWithFormat:#"%", videoURL];
NSFileManager *man = [NSFileManager defaultManager];
NSDictionary *attrs = [man attributesOfItemAtPath:yourPath error: NULL];
UInt32 result = [attrs fileSize];
//[self tweetVideoStage1:webData :result];
[self tweetVideo:webData :result :1 :#"n/a"];
}
}
-(void)tweetVideo:(NSData *)videoData :(int)videoSize :(int)mode :(NSString *)mediaID {
NSURL *twitterVideo = [NSURL URLWithString:#"https://upload.twitter.com/1.1/media/upload.json"];
// Set the parameters for the first twitter video request.
NSDictionary *postDict;
if (mode == 1) {
postDict = #{#"command": #"INIT",
#"total_bytes" : videoSize,
#"media_type" : #"video/mp4"};
}
else if (mode == 2) {
postDict = #{#"command": #"APPEND",
#"media_id" : mediaID,
#"segment_index" : #"0",
#"media" : videoData };
}
else if (mode == 3) {
postDict = #{#"command": #"FINALIZE",
#"media_id" : mediaID };
}
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL:twitterVideo parameters:postDict];
// Set the account and begin the request.
postRequest.account = account;
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error) {
if (mode == 1) {
// Parse the returned data for the JSON string
// which contains the media upload ID.
NSMutableDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error]
NSString *tweetID = [NSString stringWithFormat:#"%#", [returnedData valueForKey:#"media_id_string"]];
[self tweetVideo:videoData :result :2 :tweetID];
}
else if (mode == 2) {
[self tweetVideo:videoData :result :3 :mediaID];
}
}
else {
NSLog(#"Error stage %d - %", mode, error);
}
}];
}
Update - Twitter API errors - https://dev.twitter.com/overview/api/response-codes
In answer to your first comment, error 503 means that the Twitter servers are overloaded and can't handle your request right now.
503 Service Unavailable The Twitter servers are up, but overloaded
with requests. Try again later.
I know how to upload video to twitter use the new API. And I have tried it, it works.
Please check this: https://github.com/liu044100/SocialVideoHelper
You just need to call this class method.
+(void)uploadTwitterVideo:(NSData*)videoData account:(ACAccount*)account withCompletion:(dispatch_block_t)completion;
Hope it can resolve your problem.
Best Regards.
Been looking for sharing video on Twitter solution with below features:
Support chunk upload
Built-in support for user's credential retrieval
Since I couldn't find one meeting my need, so I decided to write one.
https://github.com/mtrung/TwitterVideoUpload
I've been testing for awhile now and it works well for me.
Hope it helps,
Regards.
Try this based in #Dan answer. It not tested, but I think it can work.
Use Cocoa-pods: pod 'TwitterKit'
if you don't use Pods try with fabric
//for Extern call
//Mode is 1
//MediaId is 0
- (void)uploadTwitterVideo:(NSData*)videoData videoTitle:(NSString *)title desc:(NSString *)desc withMode:(int)mode mediaID:(NSString *)mediaID withCompletion:(dispatch_block_t)completion
{
NSString *twitterPostURL = #"https://upload.twitter.com/1.1/media/upload.json";
NSDictionary *postParams;
if (mode == 1) {
postParams = #{#"command": #"INIT",
#"total_bytes" : [NSNumber numberWithInteger: videoData.length].stringValue,
#"media_type" : #"video/mp4"};
} else if (mode == 2) {
postParams = #{#"command": #"APPEND",
#"media_id" : mediaID,
#"segment_index" : #"0"};
} else if (mode == 3) {
postParams = #{#"command": #"FINALIZE",
#"media_id" : mediaID };
} else if (mode == 4) {
postParams = #{#"status": desc,
#"media_ids" : #[mediaID]};
}
TWTRAPIClient *twitterInstance = [[Twitter sharedInstance] APIClient];
NSError *error;
NSURLRequest *requestTw = [twitterInstance URLRequestWithMethod:#"POST" URL:twitterPostURL parameters:postParams error:&error];
[twitterInstance sendTwitterRequest:requestTw completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#"HTTP Response: %li, responseData: %#", (long)response, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
if (error) {
NSLog(#"There was an error:%#", [error localizedDescription]);
} else {
if (mode == 1) {
NSMutableDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
NSString *mediaIDResponse = [NSString stringWithFormat:#"%#", [returnedData valueForKey:#"media_id_string"]];
NSLog(#"stage one success, mediaID -> %#", mediaID);
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:2 mediaID:mediaIDResponse withCompletion:completion];
} else if (mode == 2) {
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:3 mediaID:mediaID withCompletion:completion];
} else if (mode == 3) {
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:4 mediaID:mediaID withCompletion:completion];
} else if (mode == 4) {
DispatchMainThread(^(){completion();});
}
}
}];
}
This API Works as follows.
- Login when application (twitter) is installed and when is not installed
- First priority take credential from setting
Check this case
Swift
Its very Simple.
First you need to sign in to your Twitter Account. Go to Phone Setting and click on twitter app and sign in.
Now Just Call this videoUpload func anywhere
Video or Chunked uploads Method Reference
Replace your video type/extension on that code
And Carefully read all twitter requirements.
var twitterAccount = ACAccount()
func videoUpload{
let path = Bundle.main.path(forResource: "file-Name", ofType:"mp4")
let filePath = path
var fileSize = UInt64()
do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: filePath!)
fileSize = attr[FileAttributeKey.size] as! UInt64
//if you convert to NSDictionary, you can get file size old way as well.
let dict = attr as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, error) in
if granted {
let accounts = accountStore.accounts(with: twitterAccountType)
if (accounts?.count)! > 0 {
self.twitterAccount = accounts?.last as! ACAccount
}}}
twitterAccount = Twitter.sharedInstance().sessionStore.session() as! ACAccount
uploadVideoToTwitter(videoURL: URL(string : path!)! as NSURL, fileSize: UInt32(fileSize))
}
func uploadVideoToTwitter(videoURL:NSURL,fileSize: UInt32) {
if let videoData = NSData(contentsOfFile: videoURL.path!){
self.tweetVideoInit(videoData: videoData, videoSize: Int(fileSize))
}
}
func tweetVideoInit(videoData:NSData,videoSize:Int) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "INIT"
params["total_bytes"] = String(videoData.length)
params["media_type"] = "video/mp4"
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(error as Any)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
if let tweetID = dictionary["media_id_string"] as? String{
self.tweetVideoApped(videoData: videoData, videoSize: videoSize, mediaId: tweetID, chunk: 0)
}
}
}
catch {
print(error)
}
}
})
}
func tweetVideoApped(videoData:NSData,videoSize:Int ,mediaId:String,chunk:NSInteger) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "APPEND"
params["media_id"] = mediaId
params["segment_index"] = String(chunk)
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount
postRequest?.addMultipartData(videoData as Data!, withName: "media", type: "video/mov", filename:"mediaFile")
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
self.tweetVideoFinalize(mediaId: mediaId)
}
})
}
func tweetVideoFinalize(mediaId:String) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "FINALIZE"
params["media_id"] = mediaId
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
self.postStatus(mediaId: mediaId)
}
}
catch {
print(error)
}
}
})
}
func postStatus(mediaId:String) {
let uploadURL = NSURL(string:"https://api.twitter.com/1.1/statuses/update.json")
var params = [String:String]()
params["status"] = "my first Video Upload"
params["media_ids"] = mediaId
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
print("video uploaded")
}
}
catch {
print(error)
}
}
})
}
I was able to upload video to twitter successfully!
Below are steps referred from twitter docs:
Request for twitter account
accountStore.requestAccessToAccounts(with: twitterAccountType,options:nil){(granted, error) in
POST media/upload (INIT)
params["command"] = "INIT"
params["total_bytes"] = String(videoData.length)
params["media_type"] = "video/mov"
POST media/upload (APPEND)
params["command"] = "APPEND"
params["media_id"] = mediaId
params["segment_index"] = String(chunk)
POST media/upload (FINALIZE)
params["command"] = "FINALIZE"
params["media_id"] = mediaId
POST media/upload
params["status"] = twitterDescription
params["media_ids"] = mediaId
Here is twitter doc link https://dev.twitter.com/rest/media/uploading-media.html
Please fine the detailed solution for video upload to twitter using SLRequest here.
http://swiftoverflow.blogspot.in/2017/04/upload-video-to-twitter-using-slrequest.html
I am trying to share location along with image to facebook. I have successfully shared image but unable to share location. Below is my code of sharing image.
UIImage *facebookImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imagesURL,str]]]];
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"New Happening created on the HappenShare mobile app." forKey:#"message"];
[params setObject:facebookImage forKey:#"picture"];
[FBRequestConnection startWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection,id result,NSError *error)
{
if (error)
{
NSLog(#"error : %#",error);
}
else
{
NSLog(#"Result : %#",result);
}
}];
Now for sharing location what parameter should I add in above code. I am attaching an image also to understand better that how the shared location will look like.Below image shows that how the image with text will indicate a location into map. Please suggest me a solution for that.
Along with "message" and you also need "place" ID to post as param.
Request for a "publish_actions" so that you can post a place/location.
Below is the code i've used:
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:#"Hello World" forKey:#"message"];
[params setObject:#"110503255682430"/*sample place id*/ forKey:#"place"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/feed" parameters:params HTTPMethod:#"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"result %#",result);
NSLog(#"error %#",error);
}];
You can also check this with the "administrator/tester" accounts given in Developer page -> your app -> Roles.
Use Graph explorer for better practice:
https://developers.facebook.com/tools/explorer/108895529478793?method=POST&path=me%2Ffeed%3F&version=v2.5&message=Hello%20world&place=110503255682430
Below code may help you in getting place id near your location:
NSMutableDictionary *params2 = [NSMutableDictionary dictionaryWithCapacity:4L];
[params2 setObject:[NSString stringWithFormat:#"%#,%#",YourLocation latitude,YourLocation longitude] forKey:#"center"]; //Hard code coordinates for test
[params2 setObject:#"place" forKey:#"type"];
[params2 setObject:#"100"/*meters*/ forKey:#"distance"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/search" parameters:params2 HTTPMethod:#"GET"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"RESPONSE!!! /search");
}];
OR
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/search?type=place¢er=YourLocationLat,YourLocationLong&distance=500" parameters:nil HTTPMethod:#"GET"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"result %#",result);
}];
Hope it helps you..
Swift 3.2 version of #Satish A answer.
func getPlaceId() {
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation = CLLocation()
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways) {
currentLocation = locManager.location!
let param = ["center":"\(currentLocation.coordinate.latitude),\(currentLocation.coordinate.longitude)","type":"place","distance":"100"]
FBSDKGraphRequest(graphPath: "/search", parameters: param).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
guard let data = result as? NSDictionary else {
return
}
guard let arrPlaceIDs = data.value(forKey: "data") as? [NSDictionary] else {
return
}
guard let firstPlace = arrPlaceIDs.first else {
return
}
//First facebook place id.
print(firstPlace.value(forKey: "id") as! String)
} else {
print(error?.localizedDescription ?? "error")
}
})
}
}
For Facebook sharing with attaching placeId
let photo = Photo(image: img, userGenerated: true)
var content = PhotoShareContent()
content.photos = [photo]
content.placeId = id //Facebook placeId
let sharer = GraphSharer(content: content)
sharer.failsOnInvalidData = true
do {
try sharer.share()
} catch {
print("errorrrr")
}
sharer.completion = { FBresult in
switch FBresult {
case .failed(let error):
print(error)
break
case .success(_):
//code
break
default:
break
}
}
You need to set the place (which is actually a Page ID) field within the POST request on /me/photos.
See https://developers.facebook.com/docs/graph-api/reference/v2.0/user/photos/#publish
On iOS, you can use the PlacePicker UI component of the FB iOS SDK for that, as described here: https://developers.facebook.com/docs/ios/ui-controls#placepicker
I'm using AFNetworking and need to cache data in one response for a several minutes. So I set NSUrlCache in app delegate and then in my request setting up it:
NSMutableURLRequest *request = //obtain request;
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
How then set expiration date: if the data was loaded more than n minutes ago, ask response from server and not from disk?
EDIT:
Assume that server doesn't support caching, I need to manage it in code.
So, I found the solution.
The idea is to use connection:willCacheResponse: method. Before cache the response it will be executed and there we can change response and return new, or return nil and the response will not be cached. As I use AFNetworking, there is a nice method in operation:
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
Add code:
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
if([connection currentRequest].cachePolicy == NSURLRequestUseProtocolCachePolicy) {
cachedResponse = [cachedResponse responseWithExpirationDuration:60];
}
return cachedResponse;
}];
Where responseWithExpirationDuration from category:
#interface NSCachedURLResponse (Expiration)
-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration;
#end
#implementation NSCachedURLResponse (Expiration)
-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration {
NSCachedURLResponse* cachedResponse = self;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[cachedResponse response];
NSDictionary *headers = [httpResponse allHeaderFields];
NSMutableDictionary* newHeaders = [headers mutableCopy];
newHeaders[#"Cache-Control"] = [NSString stringWithFormat:#"max-age=%i", duration];
[newHeaders removeObjectForKey:#"Expires"];
[newHeaders removeObjectForKey:#"s-maxage"];
NSHTTPURLResponse* newResponse = [[NSHTTPURLResponse alloc] initWithURL:httpResponse.URL
statusCode:httpResponse.statusCode
HTTPVersion:#"HTTP/1.1"
headerFields:newHeaders];
cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:newResponse
data:[cachedResponse.data mutableCopy]
userInfo:newHeaders
storagePolicy:cachedResponse.storagePolicy];
return cachedResponse;
}
#end
So, we set expiration in seconds in http header according to http/1.1
For that we need one of headers to be set up:
Expires, Cache-Control: s-maxage or max-age
Then create new cache response, because the properties is read only, and return new object.
Swift equivalent of #HotJard's solution using URLSession
extension CachedURLResponse {
func response(withExpirationDuration duration: Int) -> CachedURLResponse {
var cachedResponse = self
if let httpResponse = cachedResponse.response as? HTTPURLResponse, var headers = httpResponse.allHeaderFields as? [String : String], let url = httpResponse.url{
headers["Cache-Control"] = "max-age=\(duration)"
headers.removeValue(forKey: "Expires")
headers.removeValue(forKey: "s-maxage")
if let newResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: headers) {
cachedResponse = CachedURLResponse(response: newResponse, data: cachedResponse.data, userInfo: headers, storagePolicy: cachedResponse.storagePolicy)
}
}
return cachedResponse
}
}
Then implement URLSessionDataDelegate protocol in your custom class
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: #escaping (CachedURLResponse?) -> Void) {
if dataTask.currentRequest?.cachePolicy == .useProtocolCachePolicy {
let newResponse = proposedResponse.response(withExpirationDuration: 60)
completionHandler(newResponse)
}else {
completionHandler(proposedResponse)
}
}
Don't forget to create your configuration and session, passing in the your custom class as the delegate reference e.g.
let session = URLSession(
configuration: URLSession.shared.configuration,
delegate: *delegateReference*,
delegateQueue: URLSession.shared.delegateQueue
)
let task = session.dataTask(with: request)
task.resume()
The expiration of responses in the NSURLCache is controlled via the Cache-Control header in the HTTP response.
EDIT I see you've updated your question. If the server doesn't provide the Cache-Control header in the response, it won't be cached. Every request to that endpoint will load the endpoint rather than return a cached response.